diff --git a/.github/workflows/gradle-test.yaml b/.github/workflows/gradle-test.yaml index b2e91eac63f9..1ac0f740f84e 100644 --- a/.github/workflows/gradle-test.yaml +++ b/.github/workflows/gradle-test.yaml @@ -28,6 +28,8 @@ jobs: - samples/client/petstore/java/jersey2-java8 - samples/client/petstore/java/okhttp-gson - samples/client/petstore/java/okhttp-gson-group-parameter + - samples/client/petstore/java/okhttp + - samples/client/petstore/java/okhttp-group-parameter - samples/client/petstore/java/webclient-swagger2 - samples/client/petstore/java/native - samples/client/petstore/java/native-jakarta diff --git a/.github/workflows/samples-java-sbt.yaml b/.github/workflows/samples-java-sbt.yaml index d91055dc4545..36a9ee4896ca 100644 --- a/.github/workflows/samples-java-sbt.yaml +++ b/.github/workflows/samples-java-sbt.yaml @@ -4,9 +4,11 @@ on: push: paths: - 'samples/client/petstore/java/okhttp-gson/**' + - 'samples/client/petstore/java/okhttp/**' pull_request: paths: - 'samples/client/petstore/java/okhttp-gson/**' + - 'samples/client/petstore/java/okhttp/**' jobs: build: name: Build sbt/Java client, servers @@ -17,6 +19,7 @@ jobs: sample: # clients - samples/client/petstore/java/okhttp-gson + - samples/client/petstore/java/okhttp steps: - uses: actions/checkout@v7 - uses: actions/setup-java@v6 diff --git a/bin/configs/java-okhttp-group-parameter.yaml b/bin/configs/java-okhttp-group-parameter.yaml new file mode 100644 index 000000000000..d0fbac5b7666 --- /dev/null +++ b/bin/configs/java-okhttp-group-parameter.yaml @@ -0,0 +1,11 @@ +generatorName: java +outputDir: samples/client/petstore/java/okhttp-group-parameter +library: okhttp +inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-group-parameter.yaml +templateDir: modules/openapi-generator/src/main/resources/Java +additionalProperties: + serializationLibrary: gson + artifactId: petstore-okhttp-group-parameter + hideGenerationTimestamp: "true" + disallowAdditionalPropertiesIfNotPresent: false + useSingleRequestParameter: true diff --git a/bin/configs/java-okhttp-user-defined-templates.yaml b/bin/configs/java-okhttp-gson-user-defined-templates.yaml similarity index 100% rename from bin/configs/java-okhttp-user-defined-templates.yaml rename to bin/configs/java-okhttp-gson-user-defined-templates.yaml diff --git a/bin/configs/java-okhttp.yaml b/bin/configs/java-okhttp.yaml new file mode 100644 index 000000000000..eb1a28bbe998 --- /dev/null +++ b/bin/configs/java-okhttp.yaml @@ -0,0 +1,25 @@ +generatorName: java +outputDir: samples/client/petstore/java/okhttp +library: okhttp +inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml +templateDir: modules/openapi-generator/src/main/resources/Java +nameMappings: + _type: underscoreType + type_: typeWithUnderscore +parameterNameMappings: + _type: underscoreType + type_: typeWithUnderscore +additionalProperties: + serializationLibrary: gson + defaultToEmptyContainer: "array?|array|map?" + artifactId: petstore-okhttp + hideGenerationTimestamp: true + useOneOfDiscriminatorLookup: true + disallowAdditionalPropertiesIfNotPresent: false + removeEnumValuePrefix: true +enumNameMappings: + s: LOWER_CASE_S + S: UPPER_CASE_S +operationIdNameMappings: + getArrayOfEnums: getFakeArrayofenums + fakeHealthGet: getFakeHealth diff --git a/docs/generators/java-microprofile.md b/docs/generators/java-microprofile.md index d55748842e2b..537d276cb429 100644 --- a/docs/generators/java-microprofile.md +++ b/docs/generators/java-microprofile.md @@ -57,7 +57,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |generateBuilders|Whether to generate builders for models| |false| |generateClientAsBean|For resttemplate, restclient and webclient, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false| |generateConstructorWithAllArgs|whether to generate a constructor for all arguments| |false| -|generateInsecureTlsHook|Generate the ApiClient.disableCertificateValidation hook, which trusts all TLS certificates (default to true). Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3` libraries.| |true| +|generateInsecureTlsHook|Generate the hook that disables TLS certificate validation and trusts all certificates (default to true): ApiClient.disableCertificateValidation on jersey2/jersey3, ApiClient.setVerifyingSsl(false) on okhttp. Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3`, `okhttp` libraries.| |true| |gradleProperties|Append additional Gradle properties to the gradle.properties file| |null| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| @@ -66,7 +66,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |implicitHeadersRegex|Skip header parameters that matches given regex in the generated API methods using @ApiImplicitParams annotation. The match is case insensitive, like HTTP header names. Note: this parameter is ignored when implicitHeaders=true| |null| |invokerPackage|root package for generated code| |org.openapitools.client| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| -|library|library template (sub-template) to use|
**jersey2**
HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.18.9
**jersey3**
HTTP client: Jersey client 3.1.11. JSON processing: Jackson 2.x (3.x if `useJackson3=true`, requires Java 17+)
**feign**
HTTP client: OpenFeign 13.2.1. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**feign-hc5**
HTTP client: OpenFeign 13.2.1/HttpClient5 5.4.2. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**okhttp-gson**
[DEFAULT] HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
**retrofit2**
HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1 (Retrofit 2.5.0) or Jackson 2.18.9. Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)
**resttemplate**
HTTP client: Spring RestTemplate 5.3.33 (6.2.x if `useJakartaEe=true`, 7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.x (3.x if `useJackson3=true`)
**webclient**
HTTP client: Spring WebClient 5.1.18 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**restclient**
HTTP client: Spring RestClient 6.1.6 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**resteasy**
HTTP client: Resteasy client 4.7.6. JSON processing: Jackson 2.18.9
**vertx**
HTTP client: VertX client 3.5.2. JSON processing: Jackson 2.18.9
**google-api-client**
HTTP client: Google API client 2.2.0. JSON processing: Jackson 2.18.9
**rest-assured**
HTTP client: rest-assured 5.3.2 (6.x if `useJackson3=true`). JSON processing: Gson 2.10.1 or Jackson 2.18.9 (3.x if `useJackson3=true`, requires Java 17+). Only for Java 8 (Java 17+ if `useJackson3=true`)
**native**
HTTP client: Java native HttpClient. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`). Only for Java11+
**microprofile**
HTTP client: Microprofile client 2.0 (default, set desired version via `microprofileRestClientVersion=x.x.x`). JSON processing: JSON-B 1.0.2 or Jackson 2.18.9
**apache-httpclient**
HTTP client: Apache httpclient 5.2.1. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
|okhttp-gson| +|library|library template (sub-template) to use|
**jersey2**
HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.18.9
**jersey3**
HTTP client: Jersey client 3.1.11. JSON processing: Jackson 2.x (3.x if `useJackson3=true`, requires Java 17+)
**feign**
HTTP client: OpenFeign 13.2.1. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**feign-hc5**
HTTP client: OpenFeign 13.2.1/HttpClient5 5.4.2. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**okhttp-gson**
[DEFAULT] HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
**okhttp**
[BETA] HTTP client: OkHttp 5.4.0. JSON processing: Gson 2.10.1 (default), Jackson 2.22.1 (3.2.1 if `useJackson3=true`) or JSON-B, selected via '-DserializationLibrary'. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
**retrofit2**
HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1 (Retrofit 2.5.0) or Jackson 2.18.9. Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)
**resttemplate**
HTTP client: Spring RestTemplate 5.3.33 (6.2.x if `useJakartaEe=true`, 7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.x (3.x if `useJackson3=true`)
**webclient**
HTTP client: Spring WebClient 5.1.18 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**restclient**
HTTP client: Spring RestClient 6.1.6 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**resteasy**
HTTP client: Resteasy client 4.7.6. JSON processing: Jackson 2.18.9
**vertx**
HTTP client: VertX client 3.5.2. JSON processing: Jackson 2.18.9
**google-api-client**
HTTP client: Google API client 2.2.0. JSON processing: Jackson 2.18.9
**rest-assured**
HTTP client: rest-assured 5.3.2 (6.x if `useJackson3=true`). JSON processing: Gson 2.10.1 or Jackson 2.18.9 (3.x if `useJackson3=true`, requires Java 17+). Only for Java 8 (Java 17+ if `useJackson3=true`)
**native**
HTTP client: Java native HttpClient. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`). Only for Java11+
**microprofile**
HTTP client: Microprofile client 2.0 (default, set desired version via `microprofileRestClientVersion=x.x.x`). JSON processing: JSON-B 1.0.2 or Jackson 2.18.9
**apache-httpclient**
HTTP client: Apache httpclient 5.2.1. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
|okhttp-gson| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |microprofileFramework|Framework for microprofile. Possible values "kumuluzee"| |null| @@ -100,9 +100,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useDeductionForOneOfInterfaces|Annotate discriminator-free oneOf interfaces with Jackson's @JsonTypeInfo(use = Id.DEDUCTION) and @JsonSubTypes so the concrete subtype is resolved from the JSON field set rather than a type-tag property. Has no effect when a discriminator is present (name-based resolution is used instead). Requires subtypes to have structurally distinct sets of properties.| |false| |useEnumCaseInsensitive|Use `equalsIgnoreCase` when String for enum comparison| |false| |useGzipFeature|Send gzip-encoded requests| |false| -|useJackson3|Use Jackson 3 instead of Jackson 2. Supported for 'native', 'apache-httpclient', 'jersey3', and 'rest-assured' libraries (requires Java 17+) and for Spring 'resttemplate', 'webclient', and 'restclient' libraries (require useSpringBoot4=true).| |false| +|useJackson3|Use Jackson 3 instead of Jackson 2. Supported for 'native', 'apache-httpclient', 'jersey3', 'okhttp', and 'rest-assured' libraries (requires Java 17+) and for Spring 'resttemplate', 'webclient', and 'restclient' libraries (require useSpringBoot4=true).| |false| |useJakartaEe|whether to use Jakarta EE namespace instead of javax| |false| -|useJspecify|Use Jspecify for null checks. Only supported for [microprofile, native, restclient, resttemplate, webclient]| |false| +|useJspecify|Use Jspecify for null checks. Only supported for [microprofile, native, okhttp, restclient, resttemplate, webclient]| |false| |useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped. Only jersey2, jersey3, native, okhttp-gson support this option.| |false| |useOneOfInterfaces|whether to use a java interface to describe a set of oneOf options, where each option is a class that implements the interface| |false| |usePlayWS|Use Play! Async HTTP client (Play WS API)| |false| diff --git a/docs/generators/java.md b/docs/generators/java.md index 4ba8aee22aab..53ab5ed323ac 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -57,7 +57,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |generateBuilders|Whether to generate builders for models| |false| |generateClientAsBean|For resttemplate, restclient and webclient, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).| |false| |generateConstructorWithAllArgs|whether to generate a constructor for all arguments| |false| -|generateInsecureTlsHook|Generate the ApiClient.disableCertificateValidation hook, which trusts all TLS certificates (default to true). Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3` libraries.| |true| +|generateInsecureTlsHook|Generate the hook that disables TLS certificate validation and trusts all certificates (default to true): ApiClient.disableCertificateValidation on jersey2/jersey3, ApiClient.setVerifyingSsl(false) on okhttp. Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3`, `okhttp` libraries.| |true| |gradleProperties|Append additional Gradle properties to the gradle.properties file| |null| |groupId|groupId in generated pom.xml| |org.openapitools| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |false| @@ -66,7 +66,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |implicitHeadersRegex|Skip header parameters that matches given regex in the generated API methods using @ApiImplicitParams annotation. The match is case insensitive, like HTTP header names. Note: this parameter is ignored when implicitHeaders=true| |null| |invokerPackage|root package for generated code| |org.openapitools.client| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|
**true**
The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
**false**
The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
|true| -|library|library template (sub-template) to use|
**jersey2**
HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.18.9
**jersey3**
HTTP client: Jersey client 3.1.11. JSON processing: Jackson 2.x (3.x if `useJackson3=true`, requires Java 17+)
**feign**
HTTP client: OpenFeign 13.2.1. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**feign-hc5**
HTTP client: OpenFeign 13.2.1/HttpClient5 5.4.2. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**okhttp-gson**
[DEFAULT] HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
**retrofit2**
HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1 (Retrofit 2.5.0) or Jackson 2.18.9. Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)
**resttemplate**
HTTP client: Spring RestTemplate 5.3.33 (6.2.x if `useJakartaEe=true`, 7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.x (3.x if `useJackson3=true`)
**webclient**
HTTP client: Spring WebClient 5.1.18 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**restclient**
HTTP client: Spring RestClient 6.1.6 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**resteasy**
HTTP client: Resteasy client 4.7.6. JSON processing: Jackson 2.18.9
**vertx**
HTTP client: VertX client 3.5.2. JSON processing: Jackson 2.18.9
**google-api-client**
HTTP client: Google API client 2.2.0. JSON processing: Jackson 2.18.9
**rest-assured**
HTTP client: rest-assured 5.3.2 (6.x if `useJackson3=true`). JSON processing: Gson 2.10.1 or Jackson 2.18.9 (3.x if `useJackson3=true`, requires Java 17+). Only for Java 8 (Java 17+ if `useJackson3=true`)
**native**
HTTP client: Java native HttpClient. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`). Only for Java11+
**microprofile**
HTTP client: Microprofile client 2.0 (default, set desired version via `microprofileRestClientVersion=x.x.x`). JSON processing: JSON-B 1.0.2 or Jackson 2.18.9
**apache-httpclient**
HTTP client: Apache httpclient 5.2.1. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
|okhttp-gson| +|library|library template (sub-template) to use|
**jersey2**
HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.18.9
**jersey3**
HTTP client: Jersey client 3.1.11. JSON processing: Jackson 2.x (3.x if `useJackson3=true`, requires Java 17+)
**feign**
HTTP client: OpenFeign 13.2.1. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**feign-hc5**
HTTP client: OpenFeign 13.2.1/HttpClient5 5.4.2. JSON processing: Jackson 2.18.9 or Gson 2.10.1
**okhttp-gson**
[DEFAULT] HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
**okhttp**
[BETA] HTTP client: OkHttp 5.4.0. JSON processing: Gson 2.10.1 (default), Jackson 2.22.1 (3.2.1 if `useJackson3=true`) or JSON-B, selected via '-DserializationLibrary'. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
**retrofit2**
HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1 (Retrofit 2.5.0) or Jackson 2.18.9. Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)
**resttemplate**
HTTP client: Spring RestTemplate 5.3.33 (6.2.x if `useJakartaEe=true`, 7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.x (3.x if `useJackson3=true`)
**webclient**
HTTP client: Spring WebClient 5.1.18 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**restclient**
HTTP client: Spring RestClient 6.1.6 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
**resteasy**
HTTP client: Resteasy client 4.7.6. JSON processing: Jackson 2.18.9
**vertx**
HTTP client: VertX client 3.5.2. JSON processing: Jackson 2.18.9
**google-api-client**
HTTP client: Google API client 2.2.0. JSON processing: Jackson 2.18.9
**rest-assured**
HTTP client: rest-assured 5.3.2 (6.x if `useJackson3=true`). JSON processing: Gson 2.10.1 or Jackson 2.18.9 (3.x if `useJackson3=true`, requires Java 17+). Only for Java 8 (Java 17+ if `useJackson3=true`)
**native**
HTTP client: Java native HttpClient. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`). Only for Java11+
**microprofile**
HTTP client: Microprofile client 2.0 (default, set desired version via `microprofileRestClientVersion=x.x.x`). JSON processing: JSON-B 1.0.2 or Jackson 2.18.9
**apache-httpclient**
HTTP client: Apache httpclient 5.2.1. JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)
|okhttp-gson| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |microprofileFramework|Framework for microprofile. Possible values "kumuluzee"| |null| @@ -101,9 +101,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useDeductionForOneOfInterfaces|Annotate discriminator-free oneOf interfaces with Jackson's @JsonTypeInfo(use = Id.DEDUCTION) and @JsonSubTypes so the concrete subtype is resolved from the JSON field set rather than a type-tag property. Has no effect when a discriminator is present (name-based resolution is used instead). Requires subtypes to have structurally distinct sets of properties.| |false| |useEnumCaseInsensitive|Use `equalsIgnoreCase` when String for enum comparison| |false| |useGzipFeature|Send gzip-encoded requests| |false| -|useJackson3|Use Jackson 3 instead of Jackson 2. Supported for 'native', 'apache-httpclient', 'jersey3', and 'rest-assured' libraries (requires Java 17+) and for Spring 'resttemplate', 'webclient', and 'restclient' libraries (require useSpringBoot4=true).| |false| +|useJackson3|Use Jackson 3 instead of Jackson 2. Supported for 'native', 'apache-httpclient', 'jersey3', 'okhttp', and 'rest-assured' libraries (requires Java 17+) and for Spring 'resttemplate', 'webclient', and 'restclient' libraries (require useSpringBoot4=true).| |false| |useJakartaEe|whether to use Jakarta EE namespace instead of javax| |false| -|useJspecify|Use Jspecify for null checks. Only supported for [microprofile, native, restclient, resttemplate, webclient]| |false| +|useJspecify|Use Jspecify for null checks. Only supported for [microprofile, native, okhttp, restclient, resttemplate, webclient]| |false| |useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped. Only jersey2, jersey3, native, okhttp-gson support this option.| |false| |useOneOfInterfaces|whether to use a java interface to describe a set of oneOf options, where each option is a class that implements the interface| |false| |usePlayWS|Use Play! Async HTTP client (Play WS API)| |false| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java index 47fc8f773202..74091aeb45c9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java @@ -102,6 +102,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen public static final String JERSEY3 = "jersey3"; public static final String NATIVE = "native"; public static final String OKHTTP_GSON = "okhttp-gson"; + public static final String OKHTTP = "okhttp"; private static final Set OKHTTP_GSON_CALL_LOCALS = Set.of("basePath", "localBasePaths", "localCustomBaseUrl", "localHostIndex"); public static final String RESTEASY = "resteasy"; public static final String RESTTEMPLATE = "resttemplate"; @@ -192,7 +193,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen @Setter protected int maxAttemptsForRetry = 1; @Setter protected long waitTimeMillis = 10l; - private final Set JSPECIFY_SUPPORTED_LIBRARIES = new TreeSet<>(Arrays.asList(MICROPROFILE, RESTCLIENT, WEBCLIENT, NATIVE, RESTTEMPLATE)); + private final Set JSPECIFY_SUPPORTED_LIBRARIES = new TreeSet<>(Arrays.asList(MICROPROFILE, RESTCLIENT, WEBCLIENT, NATIVE, RESTTEMPLATE, OKHTTP)); private static class MpRestClientVersion { public final String rootPackage; @@ -294,10 +295,10 @@ public JavaClientCodegen() { cliOptions.add(CliOption.newBoolean(WEBCLIENT_BLOCKING_OPERATIONS, "Making all WebClient operations blocking(sync). Note that if on operation 'x-webclient-blocking: false' then such operation won't be sync", this.webclientBlockingOperations)); cliOptions.add(CliOption.newBoolean(GENERATE_CLIENT_AS_BEAN, "For resttemplate, restclient and webclient, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).", this.generateClientAsBean)); cliOptions.add(CliOption.newBoolean(SUPPORT_URL_QUERY, "Generate toUrlQueryString in POJO (default to true). Available on `native`, `apache-httpclient` libraries.")); - cliOptions.add(CliOption.newBoolean(GENERATE_INSECURE_TLS_HOOK, "Generate the ApiClient.disableCertificateValidation hook, which trusts all TLS certificates (default to true). Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3` libraries.", true)); + cliOptions.add(CliOption.newBoolean(GENERATE_INSECURE_TLS_HOOK, "Generate the hook that disables TLS certificate validation and trusts all certificates (default to true): ApiClient.disableCertificateValidation on jersey2/jersey3, ApiClient.setVerifyingSsl(false) on okhttp. Set to false to omit it, e.g. when static analysis flags the trust-all TrustManager it contains. Available on `jersey2`, `jersey3`, `okhttp` libraries.", true)); cliOptions.add(CliOption.newBoolean(USE_ENUM_CASE_INSENSITIVE, "Use `equalsIgnoreCase` when String for enum comparison", useEnumCaseInsensitive)); cliOptions.add(CliOption.newBoolean(FAIL_ON_UNKNOWN_PROPERTIES, "Fail Jackson de-serialization on unknown properties", this.failOnUnknownProperties)); - cliOptions.add(CliOption.newBoolean(USE_JACKSON_3, "Use Jackson 3 instead of Jackson 2. Supported for 'native', 'apache-httpclient', 'jersey3', and 'rest-assured' libraries (requires Java 17+) and for Spring 'resttemplate', 'webclient', and 'restclient' libraries (require useSpringBoot4=true).", this.useJackson3)); + cliOptions.add(CliOption.newBoolean(USE_JACKSON_3, "Use Jackson 3 instead of Jackson 2. Supported for 'native', 'apache-httpclient', 'jersey3', 'okhttp', and 'rest-assured' libraries (requires Java 17+) and for Spring 'resttemplate', 'webclient', and 'restclient' libraries (require useSpringBoot4=true).", this.useJackson3)); cliOptions.add(CliOption.newBoolean(SUPPORT_VERTX_FUTURE, "Also generate api methods that return a vertx Future instead of taking a callback. Only `vertx` supports this option. Requires vertx 4 or greater.", this.supportVertxFuture)); cliOptions.add(CliOption.newBoolean(USE_SEALED_ONE_OF_INTERFACES, "Generate the oneOf interfaces as sealed interfaces. Only supported for WebClient, RestClient and Microprofile (with Jackson).", this.useSealedOneOfInterfaces)); cliOptions.add(CliOption.newBoolean(USE_UNARY_INTERCEPTOR, "If true it will generate ResponseInterceptors using a UnaryOperator. This can be usefull for manipulating the request before it gets passed, for example doing your own decryption", this.useUnaryInterceptor)); @@ -310,6 +311,7 @@ public JavaClientCodegen() { supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 13.2.1. JSON processing: Jackson 2.18.9 or Gson 2.10.1"); supportedLibraries.put(FEIGN_HC5, "HTTP client: OpenFeign 13.2.1/HttpClient5 5.4.2. JSON processing: Jackson 2.18.9 or Gson 2.10.1"); supportedLibraries.put(OKHTTP_GSON, "[DEFAULT] HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'."); + supportedLibraries.put(OKHTTP, "[BETA] HTTP client: OkHttp 5.4.0. JSON processing: Gson 2.10.1 (default), Jackson 2.22.1 (3.2.1 if `useJackson3=true`) or JSON-B, selected via '-DserializationLibrary'. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 4.11.0. JSON processing: Gson 2.10.1 (Retrofit 2.5.0) or Jackson 2.18.9. Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)"); supportedLibraries.put(RESTTEMPLATE, "HTTP client: Spring RestTemplate 5.3.33 (6.2.x if `useJakartaEe=true`, 7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.x (3.x if `useJackson3=true`)"); supportedLibraries.put(WEBCLIENT, "HTTP client: Spring WebClient 5.1.18 (7.x.x if `useSpringBoot4=true`). JSON processing: Jackson 2.18.9 (3.x if `useJackson3=true`)"); @@ -407,6 +409,7 @@ public void processOpts() { final boolean libJersey3 = isLibrary(JERSEY3); final boolean libMicroprofile = isLibrary(MICROPROFILE); final boolean libNative = isLibrary(NATIVE); + final boolean libOkHttp = isLibrary(OKHTTP); final boolean libOkHttpGson = isLibrary(OKHTTP_GSON) || StringUtils.isBlank(getLibrary()); final boolean libRestAssured = isLibrary(REST_ASSURED); final boolean libRestClient = isLibrary(RESTCLIENT); @@ -424,8 +427,8 @@ public void processOpts() { convertPropertyToBooleanAndWriteBack(USE_SPRING_BOOT4, this::setUseSpringBoot4); if (useJackson3 && (libRestClient || libRestTemplate || libWebClient) && !useSpringBoot4) { throw new IllegalArgumentException("useJackson3 for the restclient, resttemplate, and webclient libraries requires useSpringBoot4=true"); - } else if (useJackson3 && !libNative && !libApache && !libJersey3 && !libRestAssured && !libRestClient && !libRestTemplate && !libWebClient) { - throw new IllegalArgumentException("useJackson3 is only supported for the 'native', 'apache-httpclient', 'jersey3', 'rest-assured', 'restclient', 'resttemplate', and 'webclient' libraries. " + + } else if (useJackson3 && !libNative && !libApache && !libJersey3 && !libOkHttp && !libRestAssured && !libRestClient && !libRestTemplate && !libWebClient) { + throw new IllegalArgumentException("useJackson3 is only supported for the 'native', 'apache-httpclient', 'jersey3', 'okhttp', 'rest-assured', 'restclient', 'resttemplate', and 'webclient' libraries. " + "The Spring libraries also require useSpringBoot4=true."); } @@ -600,7 +603,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/HttpBearerAuth.mustache", authFolder, "HttpBearerAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - if (libOkHttpGson && withAWSV4Signature) { + if ((libOkHttpGson || libOkHttp) && withAWSV4Signature) { supportingFiles.add(new SupportingFile("auth/AWS4Auth.mustache", authFolder, "AWS4Auth.java")); } } @@ -665,8 +668,8 @@ public void processOpts() { // The flag below should be set for all Java libraries, but the templates need to be ported // one by one for each library. supportsAdditionalPropertiesWithComposedSchema = true; - } else if (libOkHttpGson) { - // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call + } else if (libOkHttpGson || libOkHttp) { + // the "okhttp-gson" and "okhttp" library templates require "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); @@ -678,7 +681,12 @@ public void processOpts() { // NOTE: below moved to postProcessOperationsWithModels //supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); //supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java")); - forceSerializationLibrary(SERIALIZATION_LIBRARY_GSON); + + // "okhttp-gson" is Gson-only by definition; "okhttp" drives Gson, Jackson and JSON-B from + // the same templates, so it must keep whatever serializationLibrary the user asked for. + if (libOkHttpGson) { + forceSerializationLibrary(SERIALIZATION_LIBRARY_GSON); + } // Composed schemas can have the 'additionalProperties' keyword, as specified in JSON schema. // In principle, this should be enabled by default for all code generators. However due to limitations @@ -885,7 +893,7 @@ public void processOpts() { additionalProperties.remove(SERIALIZATION_LIBRARY_GSON); additionalProperties.remove(SERIALIZATION_LIBRARY_JSONB); supportingFiles.add(new SupportingFile("RFC3339DateFormat.mustache", invokerFolder, "RFC3339DateFormat.java")); - if (!useJackson3 || libNative || libApache || libJersey3 || libRestTemplate || libWebClient) { + if (!useJackson3 || libNative || libApache || libJersey3 || libOkHttp || libRestTemplate || libWebClient) { supportingFiles.add(new SupportingFile("RFC3339InstantDeserializer.mustache", invokerFolder, "RFC3339InstantDeserializer.java")); supportingFiles.add(new SupportingFile("RFC3339JavaTimeModule.mustache", invokerFolder, "RFC3339JavaTimeModule.java")); } @@ -907,6 +915,43 @@ public void processOpts() { break; } + if (libOkHttp) { + // `defaultToEmptyContainer` is a RULE STRING, not a boolean, but nothing validates it: + // DefaultCodegen parses the value and merely LOGs unrecognised tokens, then sets the + // defaultToEmptyContainer flag to true unconditionally. So `defaultToEmptyContainer=true` + // - the spelling every other boolean option in the generator uses - matches no rule, and + // the result is silently the OPPOSITE of the option's documented effect: containers end + // up defaulting to null. Fail fast instead of generating misleading code. Validating it + // for every generator belongs upstream in DefaultCodegen; this is gated to okhttp. + Object emptyContainerRule = additionalProperties.get(CodegenConstants.DEFAULT_TO_EMPTY_CONTAINER); + if (emptyContainerRule instanceof String && !StringUtils.isBlank((String) emptyContainerRule)) { + for (String rule : ((String) emptyContainerRule).split("\\|")) { + String containerType = rule.replaceAll("^\\?|\\?$", ""); + if (!"array".equalsIgnoreCase(containerType) && !"map".equalsIgnoreCase(containerType)) { + throw new IllegalArgumentException(String.format(Locale.ROOT, + "Invalid %s value '%s': '%s' is not a container type. This option takes " + + "'|'-separated rules over 'array' and 'map', each optionally " + + "prefixed with '?' (nullable) and/or suffixed with '?' (optional), " + + "e.g. 'array|map' or '?array?|map'. It is not a boolean - passing " + + "'true' silently makes containers default to null instead.", + CodegenConstants.DEFAULT_TO_EMPTY_CONTAINER, emptyContainerRule, rule)); + } + } + } + // The okhttp templates emit Gson, Jackson or JSON-B from one source, so they need the + // resolved serialization library as three mutually exclusive mustache flags. This must run + // after the switch above, which is where getSerializationLibrary() becomes authoritative. + additionalProperties.put("isGson", SERIALIZATION_LIBRARY_GSON.equals(getSerializationLibrary())); + additionalProperties.put("isJackson", SERIALIZATION_LIBRARY_JACKSON.equals(getSerializationLibrary())); + additionalProperties.put("isJsonb", SERIALIZATION_LIBRARY_JSONB.equals(getSerializationLibrary())); + // The okhttp templates never wrap fields in JsonNullable, so openApiNullable would only + // emit dead equalsNullable/hashCodeNullable helpers, unused imports and (for JSON-B) an + // unresolvable jackson-databind-nullable reference. Force it off for every serialization + // library rather than pretending the absent-vs-explicit-null distinction is supported. + openApiNullable = false; + additionalProperties.put(OPENAPI_NULLABLE, false); + } + if (isLibrary(FEIGN)) { additionalProperties.put("feign-okhttp", "true"); } else if (isLibrary(FEIGN_HC5)) { @@ -928,6 +973,10 @@ public void processOpts() { if (libOkHttpGson) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java")); + } else if (libOkHttp) { + // okhttp's RetryingOAuth is self-contained (it embeds TokenRequestBuilder and talks to + // OkHttp directly), so it needs neither OAuthOkHttpClient nor the Apache Oltu dependency. + supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java")); } // google-api-client doesn't use the OpenAPI auth, because it uses Google Credential directly (HttpRequestInitializer) @@ -950,7 +999,7 @@ public void processOpts() { public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { super.postProcessOperationsWithModels(objs, allModels); - if (this.getSingleRequestParameter() && (isLibrary(JERSEY2) || isLibrary(JERSEY3) || isLibrary(OKHTTP_GSON) || isLibrary(NATIVE))) { + if (this.getSingleRequestParameter() && (isLibrary(JERSEY2) || isLibrary(JERSEY3) || isLibrary(OKHTTP_GSON) || isLibrary(OKHTTP) || isLibrary(NATIVE))) { // loop through operations to set x-group-parameters extension to true if useSingleRequestParameter option is enabled OperationMap operations = objs.getOperations(); if (operations != null) { @@ -1148,7 +1197,7 @@ private static boolean isMultipartType(List> consumes) { public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { super.postProcessModelProperty(model, property); - if (OKHTTP_GSON.equals(getLibrary()) + if ((OKHTTP_GSON.equals(getLibrary()) || OKHTTP.equals(getLibrary())) && property.getComposedSchemas() != null && property.getComposedSchemas().getNot() != null) { CodegenProperty notProperty = property.getComposedSchemas().getNot(); @@ -1167,7 +1216,11 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert model.imports.add("JsonProperty"); model.imports.add("JsonValue"); model.imports.add("JsonInclude"); - if (!useJackson3) { + // The okhttp pojo template emits @JsonTypeName for Jackson 3 too, so it needs the + // import on every model. Routing it through model.imports (a Set) rather than + // hardcoding it in the template keeps it from being emitted twice on the models + // that AbstractJavaCodegen already imports it for. + if (!useJackson3 || isLibrary(OKHTTP)) { model.imports.add("JsonTypeName"); } } @@ -1236,18 +1289,101 @@ public CodegenModel fromModel(String name, Schema model) { codegenModel.imports.add("Nullable"); } + if (isLibrary(OKHTTP) && !codegenModel.isEnum + && !Boolean.TRUE.equals(codegenModel.vendorExtensions.get("x-is-one-of-interface"))) { + // The okhttp library drives Gson, Jackson and JSON-B from one template set, so its model + // templates used to hardcode every symbol the generated class needs. Codegen already + // contributes several of the same symbols through model.imports - Arrays/HashMap/ArrayList for + // container properties, the Gson annotation set from postProcessModelProperty - and + // model.mustache renders that list too, so each of them was emitted twice. Contributing them + // here instead collapses the two sources: model.imports is a Set, and it becomes the single + // place the import can come from. + // + // The branch below mirrors the dispatch in model.mustache, so a model is only handed the + // symbols the partial that renders it actually emits. That is what makes this different from + // the blanket `model.imports.add("Arrays")` AbstractJavaCodegen does for jersey2/jersey3/ + // native/okhttp-gson, which leaves those libraries with an unused Arrays import on every + // composed and enum model. Symbols the templates still hardcode - HashSet, Collections, + // StringJoiner, Logger, Level, java.lang.reflect.Type - have no Java importMapping entry, so + // they cannot be routed this way; none of them is duplicated. + final boolean gson = additionalProperties.containsKey(SERIALIZATION_LIBRARY_GSON); + if (rendersAsPojo(codegenModel)) { + // Jackson models render neither openapiFields nor the Gson/JSON-B Map.Entry loops, so + // they only need Arrays for byte[] equals/hashCode and the JsonNullable hash helper, + // and Map only for the additionalProperties holder. + final boolean jackson = additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON); + if (!jackson || codegenModel.vars.stream().anyMatch(v -> v.isByteArray) + || codegenModel.vendorExtensions.containsKey("x-jackson-optional-nullable-helpers")) { + codegenModel.imports.add("Arrays"); // openapiFields/openapiRequiredFields, byte[] equals/hashCode + } + if (!jackson || codegenModel.isAdditionalPropertiesTrue) { + codegenModel.imports.add("Map"); // additionalProperties holder, Map.Entry iteration + } + if (codegenModel.isAdditionalPropertiesTrue) { + // The only other `new HashMap<>()` in pojo.mustache is the default of a map property, + // and AbstractJavaCodegen.postProcessModelProperty already imports HashMap for those. + codegenModel.imports.add("HashMap"); // additionalProperties holder + } + if (gson) { + codegenModel.imports.add("List"); // List.class in the additionalProperties adapter + codegenModel.imports.add("Set"); // Set> in validateJsonElement + codegenModel.imports.add("IOException"); // validateJsonElement, TypeAdapter read/write + codegenModel.imports.add("SerializedName"); + codegenModel.imports.add("TypeAdapter"); + codegenModel.imports.add("JsonAdapter"); + codegenModel.imports.add("JsonReader"); + codegenModel.imports.add("JsonWriter"); + } + } else { // oneof_model.mustache / anyof_model.mustache + codegenModel.imports.add("ArrayList"); // the schema registry built in the static block + codegenModel.imports.add("HashMap"); + codegenModel.imports.add("List"); + codegenModel.imports.add("Map"); + if (gson || (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON) && !useJackson3)) { + // the Gson adapter and the Jackson 2 (de)serializer signatures; Jackson 3 and + // JSON-B declare unchecked exceptions only + codegenModel.imports.add("IOException"); + } + if (gson) { + codegenModel.imports.add("SerializedName"); + codegenModel.imports.add("TypeAdapter"); + codegenModel.imports.add("JsonAdapter"); + codegenModel.imports.add("JsonReader"); + codegenModel.imports.add("JsonWriter"); + } + } + } + return codegenModel; } + /** + * Whether {@code model.mustache} renders this model through {@code pojo.mustache} rather than through + * {@code modelEnum.mustache}, {@code oneof_interface.mustache}, {@code oneof_model.mustache} or + * {@code anyof_model.mustache}. Mirrors the dispatch expression in model.mustache. + * + * @param model the model about to be rendered + * @return true when pojo.mustache is the partial that will render it + */ + private static boolean rendersAsPojo(CodegenModel model) { + return !model.isEnum + && !Boolean.TRUE.equals(model.vendorExtensions.get("x-is-one-of-interface")) + && (model.oneOf == null || model.oneOf.isEmpty()) + && (model.anyOf == null || model.anyOf.isEmpty()); + } + @Override public Map postProcessAllModels(Map objs) { objs = super.postProcessAllModels(objs); - if (isLibrary(OKHTTP_GSON)) { + if (isLibrary(OKHTTP_GSON) || isLibrary(OKHTTP)) { // gson refuses a class whose hierarchy declares two fields bound to one JSON name, so - // the okhttp-gson additionalProperties bag is declared once, on the topmost ancestor + // the okhttp-gson and okhttp additionalProperties bag is declared once, on the topmost ancestor // that has one; every descendant inherits it instead of declaring its own copy. - // A oneOf/anyOf wrapper extends AbstractOpenApiSchema, not its own parent, and has no - // bag, so nothing is inherited through it + // An okhttp-gson oneOf/anyOf wrapper extends AbstractOpenApiSchema, not its own parent, + // and has no bag, so nothing is inherited through it. The okhttp wrapper does declare the + // bag (it records the properties the matched schema did not consume), so there the walk + // continues through it like through any other ancestor + final boolean composedParentHasNoBag = isLibrary(OKHTTP_GSON); for (CodegenModel cm : getAllModels(objs).values()) { if (cm.getComposedSchemas() != null && cm.getComposedSchemas().getOneOf() != null && cm.getComposedSchemas().getOneOf().size() > GSON_ONEOF_FIELD_THRESHOLD) { @@ -1256,8 +1392,13 @@ public Map postProcessAllModels(Map objs) variant.vendorExtensions.put("x-gson-large-oneof", true); } } + if (!composedParentHasNoBag && !rendersAsPojo(cm)) { + // an okhttp wrapper extends AbstractOpenApiSchema, so it cannot inherit a bag from + // its allOf parent; it keeps declaring its own + continue; + } for (CodegenModel ancestor = cm.getParentModel(); ancestor != null; ancestor = ancestor.getParentModel()) { - if (!ancestor.oneOf.isEmpty() || !ancestor.anyOf.isEmpty()) { + if (composedParentHasNoBag && (!ancestor.oneOf.isEmpty() || !ancestor.anyOf.isEmpty())) { break; } if (ancestor.isAdditionalPropertiesTrue) { @@ -1267,9 +1408,95 @@ public Map postProcessAllModels(Map objs) } } } + if (isLibrary(OKHTTP)) { + pruneUnusedOkHttpModelImports(objs); + } return objs; } + /** + * Drops the serializer annotation imports that {@link #postProcessModelProperty} and + * {@link AbstractJavaCodegen} add to every model but that the okhttp templates only reference + * from an enum: {@code @JsonAdapter} (Gson) and {@code @JsonValue}/{@code @JsonCreator} + * (Jackson) are emitted by modelEnum/modelInnerEnum, and {@code @JsonCreator} additionally by + * the constructor that populates read-only properties. A oneOf/anyOf wrapper has no annotated + * fields, so it needs neither {@code @JsonAdapter} nor {@code @SerializedName}. + *

+ * The collection imports follow the same idea: {@code Arrays}, {@code List} and {@code Map} + * are added for every container property or by the blanket rules in {@link #fromModel}, but + * the pojo template only names them for a byte array, a declared property of that type, or the + * additionalProperties holder. Imports of sibling models are dropped as well, since every + * model lives in the model package. + * + * @param objs all models, as handed to {@link #postProcessAllModels} + */ + private void pruneUnusedOkHttpModelImports(Map objs) { + for (ModelsMap modelsMap : objs.values()) { + final Set unused = new HashSet<>(); + for (ModelMap modelMap : modelsMap.getModels()) { + final CodegenModel cm = modelMap.getModel(); + if (cm.isEnum) { + continue; + } + final boolean pojo = rendersAsPojo(cm); + if (!cm.hasEnums || !pojo) { + unused.add(importMapping.get("JsonAdapter")); + unused.add(importMapping.get("JsonValue")); + if (!pojo || !cm.vendorExtensions.containsKey("x-has-readonly-properties")) { + unused.add(importMapping.get("JsonCreator")); + } + } + if (!pojo) { + unused.add(importMapping.get("SerializedName")); + continue; + } + final boolean gson = additionalProperties.containsKey(SERIALIZATION_LIBRARY_GSON); + final boolean jackson = additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON); + if (jackson && cm.vars.stream().noneMatch(v -> v.isByteArray || (v.defaultValue != null && v.defaultValue.contains("Arrays."))) + && !cm.vendorExtensions.containsKey("x-jackson-optional-nullable-helpers")) { + // not a byte[] property and not an array default built with Arrays.asList; Gson and + // JSON-B models always need it for their field lists + unused.add("java.util.Arrays"); + } + if (!cm.isAdditionalPropertiesTrue) { + if (gson && !declaresPropertyOfType(cm, "List")) { + unused.add("java.util.List"); + } + if (!gson && !declaresPropertyOfType(cm, "Map")) { + unused.add("java.util.Map"); + } + } + } + if (modelsMap.getImports() != null) { + // a sibling model needs no import: models share one package + final String siblingPrefix = modelPackage() + "."; + modelsMap.getImports().removeIf(item -> { + final String imported = item.get("import"); + return imported != null && imported.startsWith(siblingPrefix) + && imported.indexOf('.', siblingPrefix.length()) < 0; + }); + } + if (!unused.isEmpty() && modelsMap.getImports() != null) { + modelsMap.getImports().removeIf(item -> unused.contains(item.get("import"))); + } + } + } + + /** + * Whether a declared or inherited property of the model names the given collection type, as + * the property itself or nested in its generic arguments. + * + * @param cm the model + * @param simpleName the simple name of the collection type, e.g. {@code List} + * @return true when the rendered model source refers to the type through one of its properties + */ + private static boolean declaresPropertyOfType(CodegenModel cm, String simpleName) { + final java.util.regex.Pattern type = java.util.regex.Pattern.compile("(^|[^A-Za-z0-9_.])" + simpleName + "\\b"); + return java.util.stream.Stream.concat(cm.vars.stream(), cm.allVars.stream()) + .anyMatch(v -> (v.dataType != null && type.matcher(v.dataType).find()) + || (v.datatypeWithEnum != null && type.matcher(v.datatypeWithEnum).find())); + } + @Override public ModelsMap postProcessModelsEnum(ModelsMap objs) { objs = super.postProcessModelsEnum(objs); @@ -1296,7 +1523,11 @@ public ModelsMap postProcessModels(ModelsMap objs) { objs = super.postProcessModels(objs); List models = objs.getModels(); - if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { + // The x-enum-as-string rewrite below is not a Jackson nicety: a child schema that narrows an + // inherited discriminator to a single-value enum otherwise generates a getter that cannot + // override the parent's String getter. The okhttp library drives Gson, Jackson and JSON-B from + // one set of templates, so it needs the rewrite for every serialization library. + if (additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON) || isLibrary(OKHTTP)) { List> imports = objs.getImports(); for (ModelMap mo : models) { CodegenModel cm = mo.getModel(); @@ -1311,7 +1542,8 @@ public ModelsMap postProcessModels(ModelsMap objs) { } - if (addNullableImports) { + // JsonNullable and JsonIgnore are Jackson types; do not pull them into Gson or JSON-B output. + if (addNullableImports && additionalProperties.containsKey(SERIALIZATION_LIBRARY_JACKSON)) { Map imports2Classnames = new HashMap<>(); imports2Classnames.put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable"); imports2Classnames.put("NoSuchElementException", "java.util.NoSuchElementException"); @@ -1326,7 +1558,7 @@ public ModelsMap postProcessModels(ModelsMap objs) { CodegenModel cm = mo.getModel(); cm.getVendorExtensions().putIfAbsent(X_IMPLEMENTS, new ArrayList()); - if (isLibrary(JERSEY2) || isLibrary(JERSEY3) || isLibrary(NATIVE) || isLibrary(OKHTTP_GSON)) { + if (isLibrary(JERSEY2) || isLibrary(JERSEY3) || isLibrary(NATIVE) || isLibrary(OKHTTP_GSON) || isLibrary(OKHTTP)) { if (hasOneOf(cm) && cm.oneOf.contains("ModelNull")) { // if oneOf contains "null" type cm.isNullable = true; @@ -1431,8 +1663,8 @@ public Map postProcessSupportingFileData(Map obj @Override public String toParamName(String name) { String paramName = super.toParamName(name); - // the okhttp-gson call methods declare or read these names next to their parameters - if (isLibrary(OKHTTP_GSON) && OKHTTP_GSON_CALL_LOCALS.contains(paramName)) { + // the okhttp-gson and okhttp call methods declare or read these names next to their parameters + if ((isLibrary(OKHTTP_GSON) || isLibrary(OKHTTP)) && OKHTTP_GSON_CALL_LOCALS.contains(paramName)) { return "param" + StringUtils.capitalize(paramName); } return paramName; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/AbstractOpenApiSchema.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/AbstractOpenApiSchema.mustache new file mode 100644 index 000000000000..0bda27ac849e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/AbstractOpenApiSchema.mustache @@ -0,0 +1,135 @@ +{{>licenseInfo}} + +package {{modelPackage}}; + +{{#isJackson}} +import com.fasterxml.jackson.annotation.JsonValue; +{{/isJackson}} +import java.util.Objects; +import java.util.Map; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +{{>generatedAnnotation}} + +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map> getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + {{#isJackson}} + @JsonValue + {{/isJackson}} + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).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) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiCallback.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiCallback.mustache new file mode 100644 index 000000000000..8769cecb39c8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiCallback.mustache @@ -0,0 +1,50 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiClient.mustache new file mode 100644 index 000000000000..3863b67ff958 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiClient.mustache @@ -0,0 +1,2104 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +{{#dynamicOperations}} +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.Parameter.StyleEnum; +import io.swagger.v3.parser.OpenAPIV3Parser; +{{/dynamicOperations}} +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; +{{#joda}} +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +{{/joda}} +{{#hasOAuthMethods}} +import {{invokerPackage}}.auth.RetryingOAuth.TokenRequestBuilder; +{{/hasOAuthMethods}} + +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; +{{#generateInsecureTlsHook}} +import java.security.cert.CertificateException; +{{/generateInsecureTlsHook}} +import java.security.cert.CertificateFactory; +import java.text.DateFormat; +{{#jsr310}} +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +{{/jsr310}} +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; +{{#hasHttpBearerMethods}} +import java.util.function.Supplier; +{{/hasHttpBearerMethods}} +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +{{#hasHttpBearerMethods}} +import {{invokerPackage}}.auth.HttpBearerAuth; +{{/hasHttpBearerMethods}} +import {{invokerPackage}}.auth.ApiKeyAuth; +{{#hasOAuthMethods}} +import {{invokerPackage}}.auth.OAuth; +import {{invokerPackage}}.auth.RetryingOAuth; +import {{invokerPackage}}.auth.OAuthFlow; +{{/hasOAuthMethods}} +{{#withAWSV4Signature}} +import {{invokerPackage}}.auth.AWS4Auth; +{{/withAWSV4Signature}} + +/** + *

ApiClient class.

+ */ +public class ApiClient { + + protected String basePath = "{{{basePath}}}"; + protected List servers = new ArrayList({{#servers}}{{#-first}}Arrays.asList( +{{/-first}} new ServerConfiguration( + "{{{url}}}", + "{{{description}}}{{^description}}No description provided{{/description}}", + new HashMap(){{#variables}}{{#-first}} {{ +{{/-first}} put("{{{name}}}", new ServerVariable( + "{{{description}}}{{^description}}No description provided{{/description}}", + "{{{defaultValue}}}", + new HashSet( + {{#enumValues}} + {{#-first}} + Arrays.asList( + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ) + {{/-last}} + {{/enumValues}} + ) + )); + {{#-last}} + }}{{/-last}}{{/variables}} + ){{^-last}},{{/-last}} + {{#-last}} + ){{/-last}}{{/servers}}); + 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; + {{#generateInsecureTlsHook}} + protected boolean verifyingSsl; + {{/generateInsecureTlsHook}} + protected KeyManager[] keyManagers; + protected String tlsServerName; + + protected OkHttpClient httpClient; + protected JSON json; + + protected HttpLoggingInterceptor loggingInterceptor; + + {{#dynamicOperations}} + protected Map operationLookupMap = new HashMap<>(); + + {{/dynamicOperations}} + /** + * Basic constructor for ApiClient + */ + public ApiClient() { + init(); + initHttpClient(); + + // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{#isBasicBearer}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}{{#withAWSV4Signature}} + authentications.put("AWS4Auth", new AWS4Auth());{{/withAWSV4Signature}} + // 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).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{#isBasicBearer}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}}{{#withAWSV4Signature}} + authentications.put("AWS4Auth", new AWS4Auth());{{/withAWSV4Signature}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + {{#hasOAuthMethods}} + {{#oauthMethods}} + {{#-first}} + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID + * + * @param clientId client ID + */ + public ApiClient(String clientId) { + this(clientId, null, null); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID and additional parameters + * + * @param clientId client ID + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, Map parameters) { + this(clientId, null, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID, secret, and additional parameters + * + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, String clientSecret, Map parameters) { + this(null, clientId, clientSecret, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters + * + * @param basePath base path + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String basePath, String clientId, String clientSecret, Map parameters) { + init(); + if (basePath != null) { + this.basePath = basePath; + } + + String tokenUrl = "{{{tokenUrl}}}"; + if (!"".equals(tokenUrl) && !URI.create(tokenUrl).isAbsolute()) { + URI uri = URI.create(getBasePath()); + tokenUrl = uri.getScheme() + ":" + + (uri.getAuthority() != null ? "//" + uri.getAuthority() : "") + + tokenUrl; + if (!URI.create(tokenUrl).isAbsolute()) { + throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL"); + } + } + RetryingOAuth retryingOAuth = new RetryingOAuth(tokenUrl, clientId, OAuthFlow.{{#lambda.uppercase}}{{#lambda.snakecase}}{{flow}}{{/lambda.snakecase}}{{/lambda.uppercase}}, clientSecret, parameters); + authentications.put( + "{{name}}", + retryingOAuth + ); + initHttpClient(Collections.singletonList(retryingOAuth)); + // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{#isBasicBearer}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{/authMethods}}{{#withAWSV4Signature}} + authentications.put("AWS4Auth", new AWS4Auth());{{/withAWSV4Signature}} + + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + {{/-first}} + {{/oauthMethods}} + {{/hasOAuthMethods}} + 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); + } + {{#useGzipFeature}} + // Enable gzip request compression + builder.addInterceptor(new GzipRequestInterceptor()); + {{/useGzipFeature}} + + httpClient = builder.build(); + } + + protected void init() { + {{#generateInsecureTlsHook}} + verifyingSsl = true; + + {{/generateInsecureTlsHook}} + json = new JSON(); + + // Set default User-Agent. + setUserAgent("{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}"); + + authentications = new HashMap(); + {{#dynamicOperations}} + + OpenAPI openAPI = new OpenAPIV3Parser().read("openapi/openapi.yaml"); + createOperationLookupMap(openAPI); + {{/dynamicOperations}} + } + + /** + * Get base path + * + * @return Base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g {{{basePath}}}) + * @return An instance of ApiClient + */ + 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 ApiClient + * @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; + } + + {{#generateInsecureTlsHook}} + /** + * 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; + } + + {{/generateInsecureTlsHook}} + /** + * 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; + } + + /** + * Get TLS server name for SNI (Server Name Indication). + * + * @return The TLS server name + */ + public String getTlsServerName() { + return tlsServerName; + } + + /** + * Set TLS server name for SNI (Server Name Indication). + * This is used to verify the server certificate against a specific hostname + * instead of the hostname in the URL. + * + * @param tlsServerName The TLS server name to use for certificate verification + * @return ApiClient + */ + public ApiClient setTlsServerName(String tlsServerName) { + this.tlsServerName = tlsServerName; + 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 {{invokerPackage}}.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 {{invokerPackage}}.ApiClient} object + */ + public ApiClient setSqlDateFormat(DateFormat dateFormat) { + JSON.setSqlDateFormat(dateFormat); + return this; + } + + {{#joda}} + public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.setDateTimeFormat(dateFormat); + return this; + } + + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + {{/joda}} + {{#jsr310}} + /** + *

Set OffsetDateTimeFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link {{invokerPackage}}.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 {{invokerPackage}}.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + {{^isJackson}}{{! Jackson has no LocalDateTime adapter to reconfigure; Gson and JSON-B do. }} + /** + *

Set LocalDateTimeFormat.

+ * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link {{invokerPackage}}.ApiClient} object + */ + public ApiClient setLocalDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateTimeFormat(dateFormat); + return this; + } + + {{/isJackson}} + {{/jsr310}} + {{^isJsonb}}{{! JSON-B has no equivalent of Gson's lenient mode or Jackson's ALLOW_* read features. }} + /** + *

Set LenientOnJson.

+ * + * @param lenientOnJson a boolean + * @return a {@link {{invokerPackage}}.ApiClient} object + */ + public ApiClient setLenientOnJson(boolean lenientOnJson) { + JSON.setLenientOnJson(lenientOnJson); + return this; + } + + {{/isJsonb}} + + /** + * 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); + } + + {{#hasHttpBearerMethods}} + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + setBearerToken(() -> bearerToken); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier The supplier of bearer tokens + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + {{/hasHttpBearerMethods}} + + /** + * 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) { + {{#hasOAuthMethods}} + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + {{/hasOAuthMethods}} + 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) { + {{#withAWSV4Signature}} + for (Authentication auth : authentications.values()) { + if (auth instanceof AWS4Auth) { + ((AWS4Auth) auth).setCredentials(accessKey, secretKey); + ((AWS4Auth) auth).setRegion(region); + ((AWS4Auth) auth).setService(service); + return; + } + } + {{/withAWSV4Signature}} + 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) { + {{#withAWSV4Signature}} + for (Authentication auth : authentications.values()) { + if (auth instanceof AWS4Auth) { + ((AWS4Auth) auth).setCredentials(accessKey, secretKey, sessionToken); + ((AWS4Auth) auth).setRegion(region); + ((AWS4Auth) auth).setService(service); + return; + } + } + {{/withAWSV4Signature}} + 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; + } + + {{#hasOAuthMethods}} + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * + * @return Token request builder + */ + public TokenRequestBuilder getTokenEndPoint() { + for (Authentication apiAuth : authentications.values()) { + if (apiAuth instanceof RetryingOAuth) { + RetryingOAuth retryingOAuth = (RetryingOAuth) apiAuth; + return retryingOAuth.getTokenRequestBuilder(); + } + } + return null; + } + {{/hasOAuthMethods}} + + /** + * 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 {{#joda}}|| param instanceof DateTime || param instanceof LocalDate{{/joda}}{{#jsr310}}|| param instanceof OffsetDateTime || param instanceof LocalDate{{/jsr310}}) { + //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); + } + } + + /** + * Format the given parameter object as an ASCII-safe JSON string. + * + * @param param Parameter + * @return JSON representation of the parameter + */ + public String parameterToJsonString(Object param) { + if (param == null) { + return ""; + } + String json = this.json.serialize(param); + int firstUnsafe = -1; + for (int i = 0; i < json.length(); i++) { + if (json.charAt(i) >= 0x7f) { + firstUnsafe = i; + break; + } + } + if (firstUnsafe == -1) { + return json; + } + + StringBuilder escaped = new StringBuilder(json.length()); + escaped.append(json, 0, firstUnsafe); + for (int i = firstUnsafe; i < json.length(); i++) { + char c = json.charAt(i); + if (c >= 0x7f) { + escaped.append("\\u"); + escaped.append(Character.forDigit((c >> 12) & 0xf, 16)); + escaped.append(Character.forDigit((c >> 8) & 0xf, 16)); + escaped.append(Character.forDigit((c >> 4) & 0xf, 16)); + escaped.append(Character.forDigit(c & 0xf, 16)); + } else { + escaped.append(c); + } + } + + return escaped.toString(); + } + + /** + * 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; + } + + {{^dynamicOperations}} + /** + * 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; + } + + // escape all delimiters except commas, which are URI reserved characters + String separator = collectionFormatSeparator(collectionFormat); + String delimiter = ",".equals(separator) ? separator : escapeString(separator); + + 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; + } + {{/dynamicOperations}} + {{#dynamicOperations}} + public List parameterToPairs(Parameter param, Collection value) { + List params = new ArrayList(); + + // preconditions + if (param == null || param.getName() == null || param.getName().isEmpty() || value == null || value.isEmpty()) { + return params; + } + + // create the params based on the collection format + if (StyleEnum.FORM.equals(param.getStyle()) && Boolean.TRUE.equals(param.getExplode())) { + for (Object item : value) { + params.add(new Pair(param.getName(), 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 (StyleEnum.SPACEDELIMITED.equals(param.getStyle())) { + delimiter = escapeString(" "); + } else if (StyleEnum.PIPEDELIMITED.equals(param.getStyle())) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(param.getName(), sb.substring(delimiter.length()))); + + return params; + } + {{/dynamicOperations}} + + /** + * 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); + } + + String delimiter = collectionFormatSeparator(collectionFormat); + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Returns the separator between the items of a collection serialized in the + * given collection format. + * + * @param collectionFormat The collection format of the parameter ("csv" when unrecognized). + * @return The separator string. + */ + protected String collectionFormatSeparator(String collectionFormat) { + if ("ssv".equals(collectionFormat)) { + return " "; + } else if ("tsv".equals(collectionFormat)) { + return "\t"; + } else if ("pipes".equals(collectionFormat)) { + return "|"; + } + // collectionFormat is assumed to be "csv" by default + return ","; + } + + /** + * 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 {{invokerPackage}}.ApiException If fail to deserialize response body, i.e. cannot read response body, + * the body does not match the return type, or the Content-Type of the response is not supported. + * The exception carries the status code and headers of the response. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if (byte[].class.equals(returnType) || "byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e.getMessage(), e, response.code(), response.headers().toMultimap()); + } + } 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)) { + if (returnType.equals(String.class)) { + String respBodyString = respBody.string(); + if (respBodyString.isEmpty()) { + return null; + } + // Use String-based deserialize for String return type with fallback + return json.deserialize(respBodyString, returnType); + } else { + // Use InputStream-based deserialize which supports responses > 2GB + 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 | RuntimeException e) { + // The body could not be read or does not match the expected type. Serializers report + // that differently, some with an unchecked exception and some with an IOException, + // so it is always surfaced as an ApiException + // that keeps the status and headers of the response it belongs to. The body itself + // was consumed as a stream and is not available any more. + throw new ApiException( + "Failed to deserialize the response body as " + returnType + ": " + e.getMessage(), + e, + response.code(), + response.headers().toMultimap()); + } + } + + /** + * 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 {{invokerPackage}}.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 {{invokerPackage}}.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); + try(ResponseBody body = response.body(); BufferedSink sink = Okio.buffer(Okio.sink(file))) { + sink.writeAll(body.source()); + } + 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 {{invokerPackage}}.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 {{invokerPackage}}.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); + } + } + + {{#supportStreaming}} + /** + *

Execute stream.

+ * + * @param call a {@link okhttp3.Call} object + * @param returnType a {@link java.lang.reflect.Type} object + * @return a {@link java.io.InputStream} object + * @throws {{invokerPackage}}.ApiException if any. + */ + public InputStream executeStream(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + if (!response.isSuccessful()) { + 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); + } + if (response.body() == null) { + return null; + } + return response.body().byteStream(); + } catch (IOException e) { + throw new ApiException(e); + } + } + + {{/supportStreaming}} + /** + * {@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()); + response.close(); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + response.close(); + 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 {{invokerPackage}}.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 {{invokerPackage}}.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 {{invokerPackage}}.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); + + byte[] localVarPayload = requestBodyToBytes(reqBody); + + // update parameters with authentication settings + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RuntimeException("Authentication undefined: " + authName); + } + {{#withAWSV4Signature}} + if (!(auth instanceof AWS4Auth)) { + URI currentUri = URI.create(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); + auth.applyToParams(updatedQueryParams, headerParams, cookieParams, localVarPayload, method, currentUri); + } + {{/withAWSV4Signature}} + {{^withAWSV4Signature}} + URI currentUri = URI.create(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); + auth.applyToParams(updatedQueryParams, headerParams, cookieParams, localVarPayload, method, currentUri); + {{/withAWSV4Signature}} + } + {{#withAWSV4Signature}} + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth instanceof AWS4Auth) { + URI currentUri = URI.create(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); + auth.applyToParams(updatedQueryParams, headerParams, cookieParams, localVarPayload, method, currentUri); + } + } + {{/withAWSV4Signature}} + + 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( + java.util.Locale.ROOT, + "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(java.util.Locale.ROOT, "%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format(java.util.Locale.ROOT, "%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * 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 + * {{#generateInsecureTlsHook}}verifyingSsl and {{/generateInsecureTlsHook}}sslCaCert. + */ + protected void applySslSettings() { + try { + {{#generateInsecureTlsHook}} + 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 { + trustManagers = trustedTrustManagers(); + hostnameVerifier = trustedHostnameVerifier(); + } + {{/generateInsecureTlsHook}} + {{^generateInsecureTlsHook}} + TrustManager[] trustManagers = trustedTrustManagers(); + HostnameVerifier hostnameVerifier = trustedHostnameVerifier(); + {{/generateInsecureTlsHook}} + + 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); + } + } + + /** + * Build the trust managers that verify server certificates against the JVM's + * trust store, or against sslCaCert when one is configured. + * + * @return The trust managers to initialize the client's SSLContext with + * @throws GeneralSecurityException if sslCaCert cannot be loaded into a key store + */ + protected TrustManager[] trustedTrustManagers() throws GeneralSecurityException { + 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); + } + return trustManagerFactory.getTrustManagers(); + } + + /** + * Build the hostname verifier for TLS connections, honoring tlsServerName when set. + * + * @return The hostname verifier to configure the http client with + */ + protected HostnameVerifier trustedHostnameVerifier() { + if (tlsServerName != null && !tlsServerName.isEmpty()) { + return new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + // Verify the certificate against tlsServerName instead of the actual hostname + return OkHostnameVerifier.INSTANCE.verify(tlsServerName, session); + } + }; + } + return OkHostnameVerifier.INSTANCE; + } + + 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); + } + } + {{#dynamicOperations}} + + public ApiClient createOperationLookupMap(OpenAPI openAPI) { + operationLookupMap = new HashMap<>(); + for (Map.Entry pathItemEntry : openAPI.getPaths().entrySet()) { + String path = pathItemEntry.getKey(); + PathItem pathItem = pathItemEntry.getValue(); + addOperationLookupEntry(path, "GET", pathItem.getGet()); + addOperationLookupEntry(path, "PUT", pathItem.getPut()); + addOperationLookupEntry(path, "POST", pathItem.getPost()); + addOperationLookupEntry(path, "DELETE", pathItem.getDelete()); + addOperationLookupEntry(path, "OPTIONS", pathItem.getOptions()); + addOperationLookupEntry(path, "HEAD", pathItem.getHead()); + addOperationLookupEntry(path, "PATCH", pathItem.getPatch()); + addOperationLookupEntry(path, "TRACE", pathItem.getTrace()); + } + return this; + } + + protected void addOperationLookupEntry(String path, String method, Operation operation) { + if ( operation != null && operation.getOperationId() != null) { + operationLookupMap.put( + operation.getOperationId(), + new ApiOperation(path, method, operation)); + } + } + + public Map getOperationLookupMap() { + return operationLookupMap; + } + + public String fillParametersFromOperation( + Operation operation, + Map paramMap, + String path, + List queryParams, + List collectionQueryParams, + Map headerParams, + Map cookieParams + ) { + for (Map.Entry entry : paramMap.entrySet()) { + Object value = entry.getValue(); + for (Parameter param : operation.getParameters()) { + if (entry.getKey().equals(param.getName())) { + if (value == null) { + continue; + } + switch (param.getIn()) { + case "path": + path = path.replace("{" + param.getName() + "}", escapeString(value.toString())); + break; + case "query": + if (value instanceof Collection) { + collectionQueryParams.addAll(parameterToPairs(param, (Collection) value)); + } else { + queryParams.addAll(parameterToPair(param.getName(), value)); + } + break; + case "header": + if (param.getContent() != null && param.getContent().containsKey("application/json")) { + headerParams.put(param.getName(), parameterToJsonString(value)); + } else { + headerParams.put(param.getName(), parameterToString(value)); + } + break; + case "cookie": + cookieParams.put(param.getName(), parameterToString(value)); + break; + default: + throw new IllegalStateException("Unexpected param in: " + param.getIn()); + } + + } + } + } + return path; + } + {{/dynamicOperations}} + + /** + * Convert the HTTP request body to a byte array. + * + * @param requestBody The HTTP request object + * @return The byte array representation of the HTTP request body + * @throws {{invokerPackage}}.ApiException If fail to serialize the request body object into a byte array + */ + protected byte[] requestBodyToBytes(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readByteArray(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return new byte[0]; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiResponse.mustache new file mode 100644 index 000000000000..26e0df2d3f9f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ApiResponse.mustache @@ -0,0 +1,76 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.List; +import java.util.Map; +{{#caseInsensitiveResponseHeaders}} +import java.util.Locale; +import java.util.Map.Entry; +import java.util.TreeMap; +{{/caseInsensitiveResponseHeaders}} + +/** + * API response returned by API call. + */ +public class ApiResponse { + private final int statusCode; + private final Map> headers; + private final T data; + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response body + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + {{#caseInsensitiveResponseHeaders}} + Map> responseHeaders = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : headers.entrySet()){ + responseHeaders.put(entry.getKey().toLowerCase(Locale.ROOT), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.headers = {{#caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}; + this.data = data; + } + + /** + *

Get the status code.

+ * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

Get the headers.

+ * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

Get the data.

+ * + * @return the data + */ + public T getData() { + return data; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/GzipRequestInterceptor.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/GzipRequestInterceptor.mustache new file mode 100644 index 000000000000..bcaccfd1cb36 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/GzipRequestInterceptor.mustache @@ -0,0 +1,128 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + + /** + * Number of bytes handed to the sink per write while replaying a buffered body. Replaying the + * whole body in a single write would collapse an upload into one progress event, so it is + * replayed one okio segment at a time instead. + */ + private static final long WRITE_CHUNK_SIZE = 8192L; + + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + RequestBody body = originalRequest.body(); + if (body == null || originalRequest.header("Content-Encoding") != null || body.contentLength() == 0) { + return chain.proceed(originalRequest); + } + {{#withAWSV4Signature}} + + // An AWS SigV4 signature commits to a hash of the request payload, so a signed body cannot + // be re-encoded afterwards: gzipping it here would make the transmitted bytes disagree with + // the signature and AWS would reject the request. Send signed bodies uncompressed instead. + String authorization = originalRequest.header("Authorization"); + if (authorization != null && authorization.startsWith("AWS4-HMAC-SHA256")) { + return chain.proceed(originalRequest); + } + {{/withAWSV4Signature}} + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), compress(body)) + .build(); + return chain.proceed(compressedRequest); + } + + /** + * Compresses the request body while keeping upload progress reporting truthful. + * + *

Compressing drains the body up front (see {@link #forceContentLength}). Draining a + * {@link ProgressRequestBody} here would fire every upload callback, the terminal one included, + * before a single byte reached the socket, and would report the uncompressed sizes. So the body + * that the {@code ProgressRequestBody} wraps is compressed instead, and the compressed bytes are + * re-wrapped with the same callback: progress is then reported against the bytes that are + * actually transmitted, as they are transmitted. + */ + private RequestBody compress(final RequestBody body) throws IOException { + if (body instanceof ProgressRequestBody) { + ProgressRequestBody progressBody = (ProgressRequestBody) body; + return new ProgressRequestBody(forceContentLength(gzip(progressBody.getDelegate())), progressBody.getCallback()); + } + return forceContentLength(gzip(body)); + } + + /** + * The gzip body reports an unknown content length, which makes OkHttp fall back to + * "Transfer-Encoding: chunked". Servers that reject chunked request bodies then fail every + * compressed request, so buffer the compressed bytes and republish their known length. + * + *

Known limitation: the compressed body is held in memory until the request completes, so a + * very large upload can exhaust the heap. Publishing the compressed length requires compressing + * the whole body first, so the buffering is inherent to the behaviour above; clients that upload + * bodies too large to buffer should leave gzip request compression disabled. + */ + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + // clone() shares the buffered segments instead of copying them, so the body stays + // replayable (OkHttp may re-send it after a redirect or an auth challenge) without + // a second copy of the payload. Write it out in chunks so that an enclosing + // ProgressRequestBody sees the upload advance rather than one all-at-once event. + Buffer source = buffer.clone(); + while (!source.exhausted()) { + sink.write(source, Math.min(source.size(), WRITE_CHUNK_SIZE)); + } + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/JSON.mustache new file mode 100644 index 000000000000..8b66303ff3ef --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/JSON.mustache @@ -0,0 +1,1853 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +{{^isJackson}} +import {{modelPackage}}.AbstractOpenApiSchema; +{{/isJackson}} + +{{#isGson}} +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +{{/isGson}} +{{#isJackson}} +import {{jacksonPackage}}.core.JsonGenerator; +import {{jacksonPackage}}.core.JsonParser; +{{#useJackson3}} +import {{jacksonPackage}}.core.JacksonException; +import {{jacksonPackage}}.core.json.JsonReadFeature; +{{/useJackson3}} +import com.fasterxml.jackson.annotation.*; +import {{jacksonPackage}}.databind.*; +import {{jacksonPackage}}.databind.json.JsonMapper; +import {{jacksonPackage}}.databind.module.SimpleModule; +{{^useJackson3}} +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +{{/useJackson3}} +{{#useJackson3}} +import {{jacksonPackage}}.databind.cfg.DateTimeFeature; +import {{jacksonPackage}}.databind.cfg.EnumFeature; +{{/useJackson3}} +{{#openApiNullable}} +import org.openapitools.jackson.nullable.{{#useJackson3}}JsonNullableJackson3Module{{/useJackson3}}{{^useJackson3}}JsonNullableModule{{/useJackson3}}; +{{/openApiNullable}} +{{/isJackson}} +{{#isJsonb}} +import jakarta.json.bind.Jsonb; +import jakarta.json.bind.JsonbBuilder; +import jakarta.json.bind.JsonbConfig; +import jakarta.json.bind.adapter.JsonbAdapter; +import jakarta.json.bind.config.BinaryDataStrategy; +import java.io.File; +{{/isJsonb}} + +{{#joda}} +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +{{#isGson}} +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.DateTimeFormatterBuilder; +import org.joda.time.format.ISODateTimeFormat; +{{/isGson}} +{{#isJsonb}} +{{! Required: the JSON-B joda adapters below, their format fields and their setters are all + typed on joda's DateTimeFormatter, and java.time's is only imported for the jsr310 date + libraries. Without these two imports JSON.java references DateTimeFormatter in 8 places + with no import at all and does not compile. }} +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.ISODateTimeFormat; +{{/isJsonb}} +{{#isJackson}} +import {{jacksonPackage}}.datatype.joda.JodaModule; +{{/isJackson}} +{{/joda}} + +{{#isGson}} +import okio.ByteString; +{{/isGson}} + +import java.io.IOException; +import java.io.InputStream; +{{#isGson}} +import java.io.InputStreamReader; +import java.io.StringReader; +{{/isGson}} +{{#isJsonb}} +import java.lang.reflect.ParameterizedType; +{{/isJsonb}} +import java.lang.reflect.Type; +{{#isGson}} +import java.nio.charset.StandardCharsets; +{{/isGson}} +import java.text.DateFormat; +{{^isJackson}} +import java.text.ParseException; +{{/isJackson}} +{{#isJackson}} +{{#legacyDates}} +import java.text.ParseException; +{{/legacyDates}} +{{/isJackson}} +{{#isGson}} +import java.text.ParsePosition; +{{/isGson}} +{{#jsr310}} +import java.time.LocalDate; +{{^isJackson}} +import java.time.LocalDateTime; +{{/isJackson}} +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +{{#isGson}} +import java.time.format.DateTimeParseException; +{{/isGson}} +{{/jsr310}} +{{^isJackson}} +import java.util.Date; +{{/isJackson}} +{{#isJackson}} +{{#legacyDates}} +import java.util.Date; +{{/legacyDates}} +import java.util.HashSet; +{{/isJackson}} +import java.util.Set; +{{^isJsonb}} +import java.util.Map; +{{/isJsonb}} +{{#isJackson}} +import java.util.HashMap; +{{/isJackson}} + +/* + * A JSON utility class + */ +public class JSON { + {{#isGson}} + private static Gson gson; + private static boolean isLenientOnJson = false; + private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + {{#joda}} + private static DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter(); + private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + {{/joda}} + {{#jsr310}} + private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private static LocalDateTimeTypeAdapter localDateTimeTypeAdapter = new LocalDateTimeTypeAdapter(); + {{/jsr310}} + private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + {{/isGson}} + {{#isJackson}} + private static ObjectMapper mapper; + {{/isJackson}} + {{#isJsonb}} + {{! volatile: rebuildJsonb() swaps the instances at runtime (date-format setters) while + OkHttp dispatcher threads may be reading them. }} + private static volatile Jsonb jsonb; + private static volatile Jsonb plainJsonb; + {{! A Jsonb instance is immutable, so the configured formats are kept here and the instance is + rebuilt from scratch whenever one of them changes. }} + private static DateFormat dateFormat; + private static DateFormat sqlDateFormat; + {{#jsr310}} + private static DateTimeFormatter offsetDateTimeFormat; + private static DateTimeFormatter localDateFormat; + private static DateTimeFormatter localDateTimeFormat; + {{/jsr310}} + {{#joda}} + private static DateTimeFormatter dateTimeFormat; + private static DateTimeFormatter jodaLocalDateFormat; + {{/joda}} + {{/isJsonb}} + + static { + ensureInitialized(); + } + + public JSON() { + ensureInitialized(); + } + + {{! The shared serializer is static and the models call JSON.getGson()/getMapper()/getJsonb() + statically (Pet.fromJson(), toJson(), the TypeAdapters/deserializers), so it must exist + before any ApiClient or JSON instance has been constructed. }} + private static synchronized void ensureInitialized() { + {{#isGson}} + if (gson != null) { + // the shared static Gson is already built; rebuilding would discard a + // customization installed through setGson() + return; + } + GsonFireBuilder fireBuilder = new GsonFireBuilder(); + {{#models}} + {{#model}} + {{#discriminator}} + fireBuilder.registerTypeSelector({{modelPackage}}.{{classname}}.class, new io.gsonfire.TypeSelector<{{modelPackage}}.{{classname}}>() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + {{#mappedModels}} + classByDiscriminatorValue.put("{{mappingName}}"{{^discriminatorCaseSensitive}}.toUpperCase(java.util.Locale.ROOT){{/discriminatorCaseSensitive}}, {{modelPackage}}.{{modelName}}.class); + {{/mappedModels}} + classByDiscriminatorValue.put("{{name}}"{{^discriminatorCaseSensitive}}.toUpperCase(java.util.Locale.ROOT){{/discriminatorCaseSensitive}}, {{modelPackage}}.{{classname}}.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "{{{propertyBaseName}}}")); + } + }); + {{/discriminator}} + {{/model}} + {{/models}} + GsonBuilder builder = fireBuilder.createGsonBuilder(); + {{#disableHtmlEscaping}} + builder.disableHtmlEscaping(); + {{/disableHtmlEscaping}} + builder.registerTypeAdapter(Date.class, dateTypeAdapter); + builder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); + {{#joda}} + builder.registerTypeAdapter(DateTime.class, dateTimeTypeAdapter); + builder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); + {{/joda}} + {{#jsr310}} + builder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); + builder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); + builder.registerTypeAdapter(LocalDateTime.class, localDateTimeTypeAdapter); + {{/jsr310}} + builder.registerTypeAdapter(byte[].class, byteArrayAdapter); + {{#models}} + {{#model}} + {{^isEnum}} + {{^hasChildren}} + builder.registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()); + {{/hasChildren}} + {{/isEnum}} + {{/model}} + {{/models}} + gson = builder.create(); + {{/isGson}} + {{#isJackson}} + if (mapper == null) { + {{^useJackson3}} + mapper = JsonMapper.builder() + .serializationInclusion(JsonInclude.Include.NON_NULL) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + {{#failOnUnknownProperties}} + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + {{/failOnUnknownProperties}} + {{^failOnUnknownProperties}} + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + {{/failOnUnknownProperties}} + .enable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()) + .addModule(new JavaTimeModule()) + .addModule(rfc3339JavaTimeModule()) + .build(); + {{#joda}} + mapper.registerModule(new JodaModule()); + {{/joda}} + {{#openApiNullable}} + mapper.registerModule(new JsonNullableModule()); + {{/openApiNullable}} + {{/useJackson3}} + {{#useJackson3}} + JsonMapper.Builder jsonMapperBuilder = JsonMapper.builder() + .changeDefaultPropertyInclusion(v -> v.withValueInclusion(JsonInclude.Include.NON_NULL)) + .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) + {{#failOnUnknownProperties}} + .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + {{/failOnUnknownProperties}} + {{^failOnUnknownProperties}} + .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + {{/failOnUnknownProperties}} + .enable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE) + .disable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(EnumFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(EnumFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()); + jsonMapperBuilder.addModule(new RFC3339JavaTimeModule()); + {{#joda}} + jsonMapperBuilder.addModule(new JodaModule()); + {{/joda}} + {{#openApiNullable}} + jsonMapperBuilder.addModule(new JsonNullableJackson3Module()); + {{/openApiNullable}} + mapper = jsonMapperBuilder.build(); + {{/useJackson3}} + } + {{/isJackson}} + {{#isJsonb}} + {{! plainJsonb is checked too: setJsonb()/setSerializer() may have installed a custom + instance before the first JSON was constructed, and the models delegate through the + companion instance regardless of which instance serves the application. }} + if (jsonb == null || plainJsonb == null) { + rebuildJsonb(); + } + {{/isJsonb}} + } + + {{#isGson}} + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue{{^discriminatorCaseSensitive}}.toUpperCase(java.util.Locale.ROOT){{/discriminatorCaseSensitive}}); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + {{/isGson}} + {{#isJackson}} + {{^useJackson3}} + {{! Deliberately NOT `new RFC3339JavaTimeModule()`. That class is a shared root template, + byte-identical to master, and on Jackson 2 it registers its deserializers from + setupModule() only AFTER calling super.setupModule(context). SimpleModule forwards + _deserializers to the context just once, and that map is created lazily by the first + addDeserializer call - so on Jackson 2 the registrations are lost entirely and the + lenient RFC3339 parsing never takes effect (e.g. "2020-01-01 12:00:00.000+02:00", with + a space instead of T, is rejected instead of normalised). Jackson 3 is unaffected + because its constructor does the registering. Building the equivalent module here fixes + the okhttp library without touching a template shared by six libraries; the upstream fix + belongs in RFC3339JavaTimeModule itself. }} + private static SimpleModule rfc3339JavaTimeModule() { + SimpleModule module = new SimpleModule("RFC3339JavaTimeModule"); + module.addDeserializer(java.time.Instant.class, RFC3339InstantDeserializer.INSTANT); + module.addDeserializer(java.time.OffsetDateTime.class, RFC3339InstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(java.time.ZonedDateTime.class, RFC3339InstantDeserializer.ZONED_DATE_TIME); + return module; + } + + {{/useJackson3}} + /** + * Returns the target model class that should be used to deserialize the input data. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param modelClass The class that contains the discriminator mappings. + * @return the target model class. + */ + public static Class getClassForElement(JsonNode node, Class modelClass) { + ClassDiscriminatorMapping cdm = modelDiscriminators.get(modelClass); + if (cdm != null) { + return cdm.getClassForElement(node, new HashSet>()); + } + return null; + } + + /** + * Helper class to register the discriminator mappings. + */ + private static class ClassDiscriminatorMapping { + // The model class name. + Class modelClass; + // The name of the discriminator property. + String discriminatorName; + // The discriminator mappings for a model class. + Map> discriminatorMappings; + + // Constructs a new class discriminator. + ClassDiscriminatorMapping(Class cls, String propertyName, Map> mappings) { + modelClass = cls; + discriminatorName = propertyName; + discriminatorMappings = new HashMap>(); + if (mappings != null) { + discriminatorMappings.putAll(mappings); + } + } + + // Return the name of the discriminator property for this model class. + String getDiscriminatorPropertyName() { + return discriminatorName; + } + + // Return the discriminator value or null if the discriminator is not + // present in the payload. + String getDiscriminatorValue(JsonNode node) { + // Determine the value of the discriminator property in the input data. + if (discriminatorName != null) { + // Get the value of the discriminator property, if present in the input payload. + node = node.get(discriminatorName); + if (node != null && node.isValueNode()) { + {{^useJackson3}} + String discrValue = node.asText(); + {{/useJackson3}} + {{#useJackson3}} + String discrValue = node.asString(); + {{/useJackson3}} + if (discrValue != null) { + return discrValue; + } + } + } + return null; + } + + /** + * Returns the target model class that should be used to deserialize the input data. + * This function can be invoked for anyOf/oneOf composed models with discriminator mappings. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param visitedClasses The set of classes that have already been visited. + * @return the target model class. + */ + Class getClassForElement(JsonNode node, Set> visitedClasses) { + if (visitedClasses.contains(modelClass)) { + // Class has already been visited. + return null; + } + // Determine the value of the discriminator property in the input data. + String discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + return null; + } + Class cls = discriminatorMappings.get(discrValue); + // It may not be sufficient to return this cls directly because that target class + // may itself be a composed schema, possibly with its own discriminator. + visitedClasses.add(modelClass); + for (Class childClass : discriminatorMappings.values()) { + ClassDiscriminatorMapping childCdm = modelDiscriminators.get(childClass); + if (childCdm == null) { + continue; + } + if (!discriminatorName.equals(childCdm.discriminatorName)) { + discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + continue; + } + } + if (childCdm != null) { + // Recursively traverse the discriminator mappings. + Class childDiscr = childCdm.getClassForElement(node, visitedClasses); + if (childDiscr != null) { + return childDiscr; + } + } + } + return cls; + } + } + + /** + * Returns true if inst is an instance of modelClass in the OpenAPI model hierarchy. + * + * The Java class hierarchy is not implemented the same way as the OpenAPI model hierarchy, + * so it's not possible to use the instanceof keyword. + * + * @param modelClass A OpenAPI model class. + * @param inst The instance object. + * @param visitedClasses The set of classes that have already been visited. + * @return true if inst is an instance of modelClass in the OpenAPI model hierarchy. + */ + public static boolean isInstanceOf(Class modelClass, Object inst, Set> visitedClasses) { + if (modelClass.isInstance(inst)) { + // This handles the 'allOf' use case with single parent inheritance. + return true; + } + if (visitedClasses.contains(modelClass)) { + // This is to prevent infinite recursion when the composed schemas have + // a circular dependency. + return false; + } + visitedClasses.add(modelClass); + + // Traverse the oneOf/anyOf composed schemas. + Map> descendants = modelDescendants.get(modelClass); + if (descendants != null) { + for (Class childType : descendants.values()) { + if (isInstanceOf(childType, inst, visitedClasses)) { + return true; + } + } + } + return false; + } + + /** + * A map of discriminators for all model classes. + */ + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap<>(); + + /** + * A map of oneOf/anyOf descendants for each model class. + */ + private static Map, Map>> modelDescendants = new HashMap<>(); + + /** + * Register a model class discriminator. + * + * @param modelClass the model class + * @param discriminatorPropertyName the name of the discriminator property + * @param mappings a map with the discriminator mappings. + */ + public static void registerDiscriminator(Class modelClass, String discriminatorPropertyName, Map> mappings) { + ClassDiscriminatorMapping m = new ClassDiscriminatorMapping(modelClass, discriminatorPropertyName, mappings); + modelDiscriminators.put(modelClass, m); + } + + /** + * Register the oneOf/anyOf descendants of the modelClass. + * + * @param modelClass the model class + * @param descendants a map of oneOf/anyOf descendants. + */ + public static void registerDescendants(Class modelClass, Map> descendants) { + modelDescendants.put(modelClass, descendants); + } + {{/isJackson}} + + /** + * Get the internal serialization object. + * + * @return serialization object + */ + public static Object getSerializer() { + {{#isGson}} + return gson; + {{/isGson}} + {{#isJackson}} + return mapper; + {{/isJackson}} + {{#isJsonb}} + return jsonb; + {{/isJsonb}} + } + + /** + * Set the internal serialization object. + * + * @param serializer serialization object + */ + public static void setSerializer(Object serializer) { + {{#isGson}} + JSON.gson = (Gson) serializer; + {{/isGson}} + {{#isJackson}} + JSON.mapper = (ObjectMapper) serializer; + {{/isJackson}} + {{#isJsonb}} + setJsonb((Jsonb) serializer); + {{/isJsonb}} + } + + {{#isJsonb}} + /** + * Helper class to get the Type of a generic class. + */ + public static class GenericType { + private final Type type; + + protected GenericType() { + Type superclass = getClass().getGenericSuperclass(); + this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0]; + } + + public Type getType() { + return type; + } + } + {{/isJsonb}} + {{#isGson}} + public static Gson getGson() { + return gson; + } + + public static void setGson(Gson gson) { + JSON.gson = gson; + } + + public static void setLenientOnJson(boolean lenientOnJson) { + JSON.isLenientOnJson = lenientOnJson; + } + + public static void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } + + public static boolean isInstanceOf(Class type, Object instance, Set> visited) { + if (instance == null) { + // null never matches a concrete schema type; nullable composed schemas accept + // null in setActualInstance before consulting this method + return false; + } + if (type.isInstance(instance)) { + return true; + } + if (instance instanceof AbstractOpenApiSchema) { + AbstractOpenApiSchema schema = (AbstractOpenApiSchema) instance; + visited.add(schema.getClass()); + for (Class allowedType : schema.getSchemas().values()) { + if (visited.contains(allowedType)) { + continue; + } + if (isInstanceOf(type, schema.getActualInstance(), visited)) { + return true; + } + } + } + return false; + } + {{/isGson}} + + {{#isJackson}} + public static ObjectMapper getMapper() { + return mapper; + } + + public static void setMapper(ObjectMapper mapper) { + JSON.mapper = mapper; + } + + public static void setDateFormat(DateFormat dateFormat) { + {{^useJackson3}} + mapper.setDateFormat(dateFormat); + {{/useJackson3}} + {{#useJackson3}} + mapper = ((JsonMapper) mapper).rebuild().defaultDateFormat(dateFormat).build(); + {{/useJackson3}} + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + {{^useJackson3}} + mapper.registerModule(new SimpleModule().addSerializer(java.sql.Date.class, new JsonSerializer() { + @Override + public void serialize(java.sql.Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(dateFormat.format(value)); + } + }).addDeserializer(java.sql.Date.class, new JsonDeserializer() { + @Override + public java.sql.Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + try { + return new java.sql.Date(dateFormat.parse(p.getText()).getTime()); + } catch (java.text.ParseException e) { + throw new IOException(e); + } + } + })); + {{/useJackson3}} + {{#useJackson3}} + mapper = ((JsonMapper) mapper).rebuild() + .addModule(new SimpleModule().addSerializer(java.sql.Date.class, new ValueSerializer() { + @Override + public void serialize(java.sql.Date value, JsonGenerator gen, SerializationContext serializers) throws JacksonException { + gen.writeString(dateFormat.format(value)); + } + }).addDeserializer(java.sql.Date.class, new ValueDeserializer() { + @Override + public java.sql.Date deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { + try { + return new java.sql.Date(dateFormat.parse(p.getString()).getTime()); + } catch (java.text.ParseException e) { + throw new IllegalArgumentException("Failed to parse java.sql.Date", e); + } + } + })) + .build(); + {{/useJackson3}} + } + + public static void setLenientOnJson(boolean lenientOnJson) { + {{^useJackson3}} + mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, lenientOnJson); + mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, lenientOnJson); + mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, lenientOnJson); + {{/useJackson3}} + {{#useJackson3}} + mapper = ((JsonMapper) mapper).rebuild() + .configure(JsonReadFeature.ALLOW_UNQUOTED_PROPERTY_NAMES, lenientOnJson) + .configure(JsonReadFeature.ALLOW_SINGLE_QUOTES, lenientOnJson) + .configure(JsonReadFeature.ALLOW_JAVA_COMMENTS, lenientOnJson) + .build(); + {{/useJackson3}} + } + {{/isJackson}} + + {{#isJsonb}} + public static Jsonb getJsonb() { + return jsonb; + } + + /** + * The Jsonb instance without the polymorphism (de)serializers of the discriminated + * hierarchy roots. The generated model classes delegate concrete subtype binding through + * it; application code should use {@link #getJsonb()}. + * + * @return the polymorphism-free Jsonb instance + */ + public static Jsonb getPlainJsonb() { + return plainJsonb; + } + + /** + * Set the Jsonb instance the application (de)serializes through. + * + *

The internal companion instance the generated models delegate through is built first + * if it does not exist yet, so a custom instance may be installed before the first + * {@link JSON} is constructed.

+ * + * @param jsonb the Jsonb instance to use + */ + public static void setJsonb(Jsonb jsonb) { + if (plainJsonb == null) { + rebuildJsonb(); + } + JSON.jsonb = jsonb; + } + + /** + * Rebuild the Jsonb instance from the currently configured formats. + * + *

A Jsonb instance cannot be reconfigured after it is built, so every format setter + * records its formatter and calls this method. Any instance previously supplied through + * {@link #setJsonb(Jsonb)} is replaced.

+ */ + private static void rebuildJsonb() { + JsonbConfig config = new JsonbConfig(); + {{! Yasson's default BinaryDataStrategy is BYTE, i.e. a JSON array of numbers; the OpenAPI + 'format: byte' contract (and the Gson/Jackson variants of this library) is base64. }} + config.withBinaryDataStrategy(BinaryDataStrategy.BASE_64); + {{! Unconditional: unlike the date adapters below there is no format to configure, and + without it every model carrying a 'format: binary' property fails to (de)serialize. }} + config.withAdapters(new FileAdapter()); + if (dateFormat != null) { + config.withAdapters(new DateAdapter(dateFormat)); + } + if (sqlDateFormat != null) { + config.withAdapters(new SqlDateAdapter(sqlDateFormat)); + } + {{#jsr310}} + if (offsetDateTimeFormat != null) { + config.withAdapters(new OffsetDateTimeAdapter(offsetDateTimeFormat)); + } + if (localDateFormat != null) { + config.withAdapters(new LocalDateAdapter(localDateFormat)); + } + if (localDateTimeFormat != null) { + config.withAdapters(new LocalDateTimeAdapter(localDateTimeFormat)); + } + {{/jsr310}} + {{#joda}} + {{! Registered unconditionally, mirroring the FileAdapter: Yasson has no built-in support + for joda types, so leaving these out until the application calls a format setter left + DateTime/LocalDate to plain bean mapping. Defaults are the ISO forms that match what + the Jackson JodaModule and the Gson joda type adapters produce. }} + config.withAdapters(new JodaDateTimeAdapter( + dateTimeFormat != null ? dateTimeFormat : ISODateTimeFormat.dateTime())); + config.withAdapters(new JodaLocalDateAdapter( + jodaLocalDateFormat != null ? jodaLocalDateFormat : ISODateTimeFormat.date())); + {{/joda}} + {{! JSON-B has no any-getter/any-setter, so models with 'additionalProperties: true' + round-trip their undeclared fields through custom (de)serializers generated into + the model. The guards mirror model.mustache's dispatch: only plain pojos define + these inner classes. }} + {{#models}} + {{#model}} + {{^isEnum}} + {{^vendorExtensions.x-is-one-of-interface}} + {{^oneOf}} + {{^anyOf}} + {{^hasChildren}} + {{#isAdditionalPropertiesTrue}} + config.withSerializers(new {{modelPackage}}.{{classname}}.CustomJsonbSerializer()); + config.withDeserializers(new {{modelPackage}}.{{classname}}.CustomJsonbDeserializer()); + {{/isAdditionalPropertiesTrue}} + {{/hasChildren}} + {{/anyOf}} + {{/oneOf}} + {{/vendorExtensions.x-is-one-of-interface}} + {{/isEnum}} + {{/model}} + {{/models}} + {{! A model that forbids additional properties binds by plain bean mapping, which drops + an undeclared key silently and ignores whether a required property is there at all; + these deserializers reject such a JSON object. They bind property by property + through the fully configured instance, so registering them here - on the companion + instance too - is what keeps a NESTED model's own checks in force. }} + {{#models}} + {{#model}} + {{^isEnum}} + {{^vendorExtensions.x-is-one-of-interface}} + {{^oneOf}} + {{^anyOf}} + {{^hasChildren}} + {{^isAdditionalPropertiesTrue}} + {{#allVars}} + {{#-first}} + config.withDeserializers(new {{modelPackage}}.{{classname}}.CustomJsonbDeserializer()); + {{/-first}} + {{/allVars}} + {{/isAdditionalPropertiesTrue}} + {{/hasChildren}} + {{/anyOf}} + {{/oneOf}} + {{/vendorExtensions.x-is-one-of-interface}} + {{/isEnum}} + {{/model}} + {{/models}} + {{! Built before the polymorphism components are added: the root (de)serializers of the + discriminated hierarchies bind concrete subtypes through this instance, which keeps + them from recursing into themselves. Everything else is already registered, so a + subtype bound through it still enforces its own required and undeclared fields. }} + plainJsonb = JsonbBuilder.create(config); + {{#models}} + {{#model}} + {{^isEnum}} + {{#hasChildren}} + config.withSerializers(new {{modelPackage}}.{{classname}}.CustomJsonbSerializer()); + config.withDeserializers(new {{modelPackage}}.{{classname}}.CustomJsonbDeserializer()); + {{/hasChildren}} + {{/isEnum}} + {{/model}} + {{/models}} + jsonb = JsonbBuilder.create(config); + } + + public static void setDateFormat(DateFormat dateFormat) { + JSON.dateFormat = dateFormat; + rebuildJsonb(); + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + JSON.sqlDateFormat = dateFormat; + rebuildJsonb(); + } + + {{! JSON-B has no equivalent of Gson's lenient mode or Jackson's ALLOW_* read features, so this + setter is not generated for JSON-B; ApiClient omits its wrapper too. }} + + /** + * JSON-B adapter for java.io.File, the mapping of {@code format: binary}. + * + *

Without it JSON-B introspects {@code File} as a bean and fails both ways: serializing + * recurses through {@code getAbsoluteFile()} and aborts with "Recursive reference has been + * found in class java.io.File", while deserializing demands {@code START_OBJECT} where the + * schema carries a string. The representation matches the Jackson serialization library: + * the absolute path on the way out, {@code new File(String)} on the way in.

+ */ + private static class FileAdapter implements JsonbAdapter { + + @Override + public String adaptToJson(File file) { + if (file == null) { + return null; + } + return file.getAbsolutePath(); + } + + @Override + public File adaptFromJson(String value) { + if (value == null) { + return null; + } + return new File(value); + } + } + + /** + * JSON-B adapter for java.util.Date driven by a configurable DateFormat. + */ + private static class DateAdapter implements JsonbAdapter { + private final DateFormat dateFormat; + + DateAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public String adaptToJson(Date date) { + if (date == null) { + return null; + } + // DateFormat is not thread-safe. + synchronized (dateFormat) { + return dateFormat.format(date); + } + } + + @Override + public Date adaptFromJson(String value) throws ParseException { + if (value == null) { + return null; + } + synchronized (dateFormat) { + return dateFormat.parse(value); + } + } + } + + /** + * JSON-B adapter for java.sql.Date driven by a configurable DateFormat. + */ + private static class SqlDateAdapter implements JsonbAdapter { + private final DateFormat dateFormat; + + SqlDateAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public String adaptToJson(java.sql.Date date) { + if (date == null) { + return null; + } + synchronized (dateFormat) { + return dateFormat.format(date); + } + } + + @Override + public java.sql.Date adaptFromJson(String value) throws ParseException { + if (value == null) { + return null; + } + synchronized (dateFormat) { + return new java.sql.Date(dateFormat.parse(value).getTime()); + } + } + } + {{#jsr310}} + + /** + * JSON-B adapter for java.time.OffsetDateTime driven by a configurable DateTimeFormatter. + */ + private static class OffsetDateTimeAdapter implements JsonbAdapter { + private final DateTimeFormatter formatter; + + OffsetDateTimeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + @Override + public String adaptToJson(OffsetDateTime value) { + return value == null ? null : formatter.format(value); + } + + @Override + public OffsetDateTime adaptFromJson(String value) { + return value == null ? null : OffsetDateTime.parse(value, formatter); + } + } + + /** + * JSON-B adapter for java.time.LocalDate driven by a configurable DateTimeFormatter. + */ + private static class LocalDateAdapter implements JsonbAdapter { + private final DateTimeFormatter formatter; + + LocalDateAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + @Override + public String adaptToJson(LocalDate value) { + return value == null ? null : formatter.format(value); + } + + @Override + public LocalDate adaptFromJson(String value) { + return value == null ? null : LocalDate.parse(value, formatter); + } + } + + /** + * JSON-B adapter for java.time.LocalDateTime driven by a configurable DateTimeFormatter. + */ + private static class LocalDateTimeAdapter implements JsonbAdapter { + private final DateTimeFormatter formatter; + + LocalDateTimeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + @Override + public String adaptToJson(LocalDateTime value) { + return value == null ? null : formatter.format(value); + } + + @Override + public LocalDateTime adaptFromJson(String value) { + return value == null ? null : LocalDateTime.parse(value, formatter); + } + } + {{/jsr310}} + {{#joda}} + + /** + * JSON-B adapter for org.joda.time.DateTime driven by a configurable DateTimeFormatter. + */ + private static class JodaDateTimeAdapter implements JsonbAdapter { + private final DateTimeFormatter formatter; + + JodaDateTimeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + @Override + public String adaptToJson(DateTime value) { + return value == null ? null : formatter.print(value); + } + + @Override + public DateTime adaptFromJson(String value) { + return value == null ? null : formatter.parseDateTime(value); + } + } + + /** + * JSON-B adapter for org.joda.time.LocalDate driven by a configurable DateTimeFormatter. + */ + private static class JodaLocalDateAdapter implements JsonbAdapter { + private final DateTimeFormatter formatter; + + JodaLocalDateAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + @Override + public String adaptToJson(LocalDate value) { + return value == null ? null : formatter.print(value); + } + + @Override + public LocalDate adaptFromJson(String value) { + return value == null ? null : formatter.parseLocalDate(value); + } + } + {{/joda}} + + public static boolean isInstanceOf(Class type, Object instance, Set> visited) { + if (instance == null) { + // null never matches a concrete schema type; nullable composed schemas accept + // null in setActualInstance before consulting this method + return false; + } + if (type.isInstance(instance)) { + return true; + } + if (instance instanceof AbstractOpenApiSchema) { + AbstractOpenApiSchema schema = (AbstractOpenApiSchema) instance; + visited.add(schema.getClass()); + for (Class allowedType : schema.getSchemas().values()) { + if (visited.contains(allowedType)) { + continue; + } + if (isInstanceOf(type, schema.getActualInstance(), visited)) { + return true; + } + } + } + return false; + } + {{/isJsonb}} + + {{#jsr310}} + {{#isGson}} + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + {{/isGson}} + {{#isJackson}} + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + {{^useJackson3}} + mapper.registerModule(new SimpleModule() + .addSerializer(OffsetDateTime.class, new JsonSerializer() { + @Override + public void serialize(OffsetDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(dateFormat.format(value)); + } + }) + .addDeserializer(OffsetDateTime.class, new JsonDeserializer() { + @Override + public OffsetDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + return OffsetDateTime.parse(p.getText(), dateFormat); + } + })); + {{/useJackson3}} + {{#useJackson3}} + mapper = ((JsonMapper) mapper).rebuild() + .addModule(new SimpleModule() + .addSerializer(OffsetDateTime.class, new ValueSerializer() { + @Override + public void serialize(OffsetDateTime value, JsonGenerator gen, SerializationContext serializers) throws JacksonException { + gen.writeString(dateFormat.format(value)); + } + }) + .addDeserializer(OffsetDateTime.class, new ValueDeserializer() { + @Override + public OffsetDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { + return OffsetDateTime.parse(p.getString(), dateFormat); + } + })) + .build(); + {{/useJackson3}} + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + {{^useJackson3}} + mapper.registerModule(new SimpleModule() + .addSerializer(LocalDate.class, new JsonSerializer() { + @Override + public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(dateFormat.format(value)); + } + }) + .addDeserializer(LocalDate.class, new JsonDeserializer() { + @Override + public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + return LocalDate.parse(p.getText(), dateFormat); + } + })); + {{/useJackson3}} + {{#useJackson3}} + mapper = ((JsonMapper) mapper).rebuild() + .addModule(new SimpleModule() + .addSerializer(LocalDate.class, new ValueSerializer() { + @Override + public void serialize(LocalDate value, JsonGenerator gen, SerializationContext serializers) throws JacksonException { + gen.writeString(dateFormat.format(value)); + } + }) + .addDeserializer(LocalDate.class, new ValueDeserializer() { + @Override + public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { + return LocalDate.parse(p.getString(), dateFormat); + } + })) + .build(); + {{/useJackson3}} + } + {{/isJackson}} + {{#isJsonb}} + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.offsetDateTimeFormat = dateFormat; + rebuildJsonb(); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.localDateFormat = dateFormat; + rebuildJsonb(); + } + + public static void setLocalDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.localDateTimeFormat = dateFormat; + rebuildJsonb(); + } + {{/isJsonb}} + {{/jsr310}} + + {{#joda}} + {{#isGson}} + public static void setDateTimeFormat(DateTimeFormatter dateFormat) { + dateTimeTypeAdapter.setFormat(dateFormat); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + {{/isGson}} + {{#isJackson}} + public static void setDateTimeFormat(org.joda.time.format.DateTimeFormatter dateFormat) { + {{^useJackson3}} + mapper.registerModule(new SimpleModule() + .addSerializer(DateTime.class, new JsonSerializer() { + @Override + public void serialize(DateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(dateFormat.print(value)); + } + }) + .addDeserializer(DateTime.class, new JsonDeserializer() { + @Override + public DateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + return dateFormat.parseDateTime(p.getText()); + } + })); + {{/useJackson3}} + {{#useJackson3}} + mapper = ((JsonMapper) mapper).rebuild() + .addModule(new SimpleModule() + .addSerializer(DateTime.class, new ValueSerializer() { + @Override + public void serialize(DateTime value, JsonGenerator gen, SerializationContext serializers) throws JacksonException { + gen.writeString(dateFormat.print(value)); + } + }) + .addDeserializer(DateTime.class, new ValueDeserializer() { + @Override + public DateTime deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { + return dateFormat.parseDateTime(p.getString()); + } + })) + .build(); + {{/useJackson3}} + } + + public static void setLocalDateFormat(org.joda.time.format.DateTimeFormatter dateFormat) { + {{^useJackson3}} + mapper.registerModule(new SimpleModule() + .addSerializer(org.joda.time.LocalDate.class, new JsonSerializer() { + @Override + public void serialize(org.joda.time.LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(dateFormat.print(value)); + } + }) + .addDeserializer(org.joda.time.LocalDate.class, new JsonDeserializer() { + @Override + public org.joda.time.LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + return dateFormat.parseLocalDate(p.getText()); + } + })); + {{/useJackson3}} + {{#useJackson3}} + mapper = ((JsonMapper) mapper).rebuild() + .addModule(new SimpleModule() + .addSerializer(org.joda.time.LocalDate.class, new ValueSerializer() { + @Override + public void serialize(org.joda.time.LocalDate value, JsonGenerator gen, SerializationContext serializers) throws JacksonException { + gen.writeString(dateFormat.print(value)); + } + }) + .addDeserializer(org.joda.time.LocalDate.class, new ValueDeserializer() { + @Override + public org.joda.time.LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { + return dateFormat.parseLocalDate(p.getString()); + } + })) + .build(); + {{/useJackson3}} + } + {{/isJackson}} + {{#isJsonb}} + public static void setDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.dateTimeFormat = dateFormat; + rebuildJsonb(); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.jodaLocalDateFormat = dateFormat; + rebuildJsonb(); + } + {{/isJsonb}} + {{/joda}} + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + {{#isGson}} + return gson.toJson(obj); + {{/isGson}} + {{#isJackson}} + try { + return mapper.writeValueAsString(obj); + } catch ({{#useJackson3}}JacksonException{{/useJackson3}}{{^useJackson3}}IOException{{/useJackson3}} e) { + throw new RuntimeException(e); + } + {{/isJackson}} + {{#isJsonb}} + return jsonb.toJson(obj); + {{/isJsonb}} + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + {{#isGson}} + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + {{/isGson}} + {{#isJackson}} + try { + JavaType type = mapper.getTypeFactory().constructType(returnType); + return mapper.readValue(body, type); + } catch ({{#useJackson3}}JacksonException{{/useJackson3}}{{^useJackson3}}IOException{{/useJackson3}} e) { + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw new RuntimeException(e); + } + } + {{/isJackson}} + {{#isJsonb}} + try { + return jsonb.fromJson(body, returnType); + } catch (jakarta.json.bind.JsonbException e) { + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw e; + } + } + {{/isJsonb}} + } + + /** + * 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 T deserialize(InputStream inputStream, Type returnType) throws IOException { + {{#isGson}} + try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(reader); + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(reader, returnType); + } + } + {{/isGson}} + {{#isJackson}} + JavaType type = mapper.getTypeFactory().constructType(returnType); + return mapper.readValue(inputStream, type); + {{/isJackson}} + {{#isJsonb}} + return jsonb.fromJson(inputStream, returnType); + {{/isJsonb}} + } + + {{#isGson}} + /** + * Gson TypeAdapter for Byte Array type + */ + public static class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + {{#joda}} + /** + * Gson TypeAdapter for Joda DateTime type + */ + public static class DateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public DateTimeTypeAdapter() { + this(new DateTimeFormatterBuilder() + .append(ISODateTimeFormat.dateTime().getPrinter(), ISODateTimeFormat.dateOptionalTimeParser().getParser()) + .toFormatter()); + } + + public DateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } + } + + /** + * Gson TypeAdapter for Joda LocalDate type + */ + public static class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(ISODateTimeFormat.date()); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } + } + + {{/joda}} + {{#jsr310}} + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public static class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public static class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDateTime type + */ + public static class LocalDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE_TIME); + } + + public LocalDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + return LocalDateTime.parse(date, formatter); + } catch (DateTimeParseException e) { + if (date.length() > 10 && date.charAt(10) == ' ') { + date = date.substring(0, 10) + 'T' + date.substring(11); + return LocalDateTime.parse(date, formatter); + } + throw e; + } + } + } + } + + public static void setLocalDateTimeFormat(DateTimeFormatter dateFormat) { + localDateTimeTypeAdapter.setFormat(dateFormat); + } + + {{/jsr310}} + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public static class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public static class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } + {{/isGson}} +{{#legacyDates}} + + {{! `dateLibrary=legacy` maps BOTH `format: date` and `format: date-time` onto + java.util.Date, so a single type-keyed (de)serializer cannot serve both. The + date-time form (a full instant, rendered in UTC) was therefore applied to + date-only properties too, which appends a time component the server rejects AND + shifts the calendar day backwards on any JVM at a positive UTC offset. The + adapter below is attached per-property from pojo.mustache, for `isDate` only, so + the public API stays java.util.Date. Jackson needs no adapter - it expresses the + same thing with a per-property @JsonFormat pattern. }} + {{! Deliberately left on the DEFAULT time zone. A `format: date` value carries no zone, so + the only sane contract is that the calendar day written out is the day the caller set: + pinning UTC re-introduces the very off-by-one-day shift this fixes, because a Date at + local midnight on the 15th is the 14th at 23:00Z. Both directions use this same format, + so the value round-trips exactly. }} + private static java.text.DateFormat dateOnlyFormat() { + return new java.text.SimpleDateFormat("yyyy-MM-dd"); + } +{{#isJackson}} + + {{! A per-property @JsonFormat(pattern="yyyy-MM-dd") would look simpler but is WRONG here: + with no explicit `timezone` it resolves against the MAPPER's default zone, and Jackson + defaults that to UTC rather than the JVM zone - so a Date at local midnight on the 15th + still serialised as "2020-01-14", and Jackson would disagree with the Gson and JSON-B + paths. Going through dateOnlyFormat() keeps all four serializers byte-identical on the + wire. }} + {{^useJackson3}} + public static class DateOnlySerializer extends JsonSerializer { + @Override + public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException { + gen.writeString(dateOnlyFormat().format(value)); + } + } + + public static class DateOnlyDeserializer extends JsonDeserializer { + @Override + public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + try { + return dateOnlyFormat().parse(p.getText()); + } catch (ParseException e) { + throw new IOException(e); + } + } + } + {{/useJackson3}} + {{#useJackson3}} + public static class DateOnlySerializer extends ValueSerializer { + @Override + public void serialize(Date value, JsonGenerator gen, SerializationContext serializers) throws JacksonException { + gen.writeString(dateOnlyFormat().format(value)); + } + } + + public static class DateOnlyDeserializer extends ValueDeserializer { + @Override + public Date deserialize(JsonParser p, DeserializationContext ctxt) throws JacksonException { + try { + return dateOnlyFormat().parse(p.getString()); + } catch (ParseException e) { + throw new IllegalArgumentException("Failed to parse a date-only java.util.Date", e); + } + } + } + {{/useJackson3}} +{{/isJackson}} +{{#isGson}} + + /** + * Gson type adapter for a date-only java.util.Date (OpenAPI {@code format: date}). + */ + public static class DateOnlyTypeAdapter extends TypeAdapter { + @Override + public void write(JsonWriter out, Date value) throws IOException { + if (value == null) { + out.nullValue(); + return; + } + out.value(dateOnlyFormat().format(value)); + } + + @Override + public Date read(JsonReader in) throws IOException { + {{! Fully qualified: the Gson import block does not pull in JsonToken (the unqualified + JsonToken in this file is Jackson's, imported only for the Jackson serializer). }} + if (in.peek() == com.google.gson.stream.JsonToken.NULL) { + in.nextNull(); + return null; + } + String date = in.nextString(); + try { + return dateOnlyFormat().parse(date); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } +{{/isGson}} +{{#isJsonb}} + + /** + * JSON-B adapter for a date-only java.util.Date (OpenAPI {@code format: date}). + */ + public static class DateOnlyJsonbAdapter implements JsonbAdapter { + @Override + public String adaptToJson(Date value) { + return value == null ? null : dateOnlyFormat().format(value); + } + + @Override + public Date adaptFromJson(String value) throws ParseException { + return value == null ? null : dateOnlyFormat().parse(value); + } + } + + {{! The generated CustomJsonbDeserializer binds each property with + jsonb.fromJson(value, fieldType(name)) - i.e. by DECLARED TYPE - so a field-level + @JsonbTypeAdapter is never consulted on that path and Yasson falls back to its own + java.util.Date parsing, which rejects a bare "yyyy-MM-dd". Deserialization of a + date-only property therefore has to go through this helper explicitly. }} + public static Date dateOnlyFromJson(jakarta.json.JsonValue value) { + try { + return dateOnlyFormat().parse(((jakarta.json.JsonString) value).getString()); + } catch (ParseException e) { + throw new jakarta.json.bind.JsonbException("Failed to parse a date-only java.util.Date: " + value, e); + } + } +{{/isJsonb}} +{{/legacyDates}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ProgressRequestBody.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ProgressRequestBody.mustache new file mode 100644 index 000000000000..aeb53cacfa39 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ProgressRequestBody.mustache @@ -0,0 +1,119 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; +import java.util.Objects; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = Objects.requireNonNull(callback); + } + + /** + * The body this one wraps. Package-private so that {@link GzipRequestInterceptor} can compress + * that body directly: draining this wrapper to compress it would report the upload as finished + * before the request reached the network. + * + * @return the wrapped request body + */ + RequestBody getDelegate() { + return requestBody; + } + + /** + * The callback this body reports upload progress to. Package-private so that + * {@link GzipRequestInterceptor} can re-wrap the compressed body with the same callback. + * + * @return the progress callback + */ + ApiCallback getCallback() { + return callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public boolean isDuplex() { + return requestBody.isDuplex(); + } + + @Override + public boolean isOneShot() { + return requestBody.isOneShot(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (isDuplex()) { + // A duplex body may keep writing on another thread after writeTo() returns, so completion + // can only be reported once the delegate closes the sink, not when this method returns. + requestBody.writeTo(Okio.buffer(new CountingSink(sink, true))); + return; + } + CountingSink countingSink = new CountingSink(sink, false); + BufferedSink bufferedSink = Okio.buffer(countingSink); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + long bytesWritten = countingSink.bytesWritten; + long contentLength = contentLength(); + callback.onUploadProgress(bytesWritten, contentLength, true); + } + + private final class CountingSink extends ForwardingSink { + + private long bytesWritten = 0L; + private long contentLength = 0L; + private final boolean reportDoneOnClose; + + public CountingSink(Sink delegate, boolean reportDoneOnClose) { + super(delegate); + this.reportDoneOnClose = reportDoneOnClose; + } + + @Override + public void close() throws IOException { + super.close(); + if (reportDoneOnClose) { + callback.onUploadProgress(bytesWritten, contentLength == 0 ? contentLength() : contentLength, true); + } + } + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + // writeTo emits the single terminal callback once the body is fully written; reporting + // done here as well would fire it twice for a known-length body. + callback.onUploadProgress(bytesWritten, contentLength, false); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ProgressResponseBody.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ProgressResponseBody.mustache new file mode 100644 index 000000000000..8357a3053b0f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/ProgressResponseBody.mustache @@ -0,0 +1,71 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + // Memoized: OkHttp calls source() again on close(), and a second ForwardingSource would + // reset the progress counter and re-wrap an already partially consumed stream. + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + boolean done = false; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + if (bytesRead == -1) { + // an exhausted source keeps answering -1 to every further read (a buffered + // reader probes it more than once), so completion is reported only once + if (!done) { + done = true; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), true); + } + return bytesRead; + } + totalBytesRead += bytesRead; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), false); + return bytesRead; + } + }; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/README.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/README.mustache new file mode 100644 index 000000000000..de3afa6c1875 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/README.mustache @@ -0,0 +1,195 @@ +# {{artifactId}} + +{{appName}} +- API version: {{appVersion}} +{{^hideGenerationTimestamp}} + - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} + - Generator version: {{generatorVersion}} + +{{{appDescriptionWithNewLines}}} + +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: +1. Java 1.8+ +2. Maven (3.8.3+)/Gradle (7.2+) + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the '{{{artifactId}}}' jar has been published to maven central. + mavenLocal() // Needed if the '{{{artifactId}}}' jar has been published to the local maven repo. + } + + dependencies { + implementation "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +* `target/{{{artifactId}}}-{{{artifactVersion}}}.jar` +* `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +// Import classes: +import {{{invokerPackage}}}.ApiClient; +import {{{invokerPackage}}}.ApiException; +import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}} +import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} +import {{{modelPackage}}}.*; +import {{{package}}}.{{{classname}}}; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("{{{basePath}}}"); + {{#withAWSV4Signature}} + // Configure AWS Signature V4 authorization + defaultClient.setAWS4Configuration("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY", "REGION", "SERVICE") + {{/withAWSV4Signature}} + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(defaultClient); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{{paramName}}}({{{paramName}}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}}{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation for Models + +{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + + +## Documentation for Authorization + +{{^authMethods}}Endpoints do not require authorization.{{/authMethods}} +{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasicBasic}}- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}}- **Type**: HTTP Bearer Token authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} +{{/isBasicBearer}} +{{#isHttpSignature}}- **Type**: HTTP signature authentication +{{/isHttpSignature}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} +{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/additional_properties.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/additional_properties.mustache new file mode 100644 index 000000000000..9b41d6c906fb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/additional_properties.mustache @@ -0,0 +1,76 @@ +{{#isAdditionalPropertiesTrue}} +{{^vendorExtensions.x-inherits-additional-properties}} + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + {{#isJackson}} + @JsonIgnore + {{/isJackson}} + {{#isJsonb}} + @JsonbTransient + {{/isJsonb}} + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the {{classname}} instance itself + */ + {{#isJackson}} + @JsonAnySetter + {{/isJackson}} + public {{classname}} putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + {{#isJackson}} + @JsonAnyGetter + {{/isJackson}} + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } +{{/vendorExtensions.x-inherits-additional-properties}} +{{#vendorExtensions.x-inherits-additional-properties}} + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * The bag is inherited from the superclass. + * + * @param key name of the property + * @param value value of the property + * @return the {{classname}} instance itself + */ + @Override + public {{classname}} putAdditionalProperty(String key, Object value) { + super.putAdditionalProperty(key, value); + return this; + } +{{/vendorExtensions.x-inherits-additional-properties}} +{{/isAdditionalPropertiesTrue}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/anyof_model.mustache new file mode 100644 index 000000000000..8636bb220f37 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/anyof_model.mustache @@ -0,0 +1,1258 @@ +{{#isGson}} +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +{{! TypeAdapter, JsonAdapter, SerializedName, JsonReader and JsonWriter are contributed via + model.imports by JavaClientCodegen; emitting them here as well produced duplicates. }} +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +{{/isGson}} +{{#isJackson}} +{{#isAdditionalPropertiesTrue}} +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +{{/isAdditionalPropertiesTrue}} +import {{jacksonPackage}}.core.JsonGenerator; +import {{jacksonPackage}}.core.JsonParser; +import {{jacksonPackage}}.core.type.TypeReference; +import {{jacksonPackage}}.databind.DeserializationContext; +{{^useJackson3}} +import {{jacksonPackage}}.databind.JsonMappingException; +{{/useJackson3}} +import {{jacksonPackage}}.databind.JsonNode; +{{^useJackson3}} +import {{jacksonPackage}}.databind.SerializerProvider; +{{/useJackson3}} +import {{jacksonPackage}}.databind.annotation.JsonDeserialize; +import {{jacksonPackage}}.databind.annotation.JsonSerialize; +import {{jacksonPackage}}.databind.deser.std.StdDeserializer; +import {{jacksonPackage}}.databind.ser.std.StdSerializer; +{{#useJackson3}} +import {{jacksonPackage}}.core.JacksonException; +import {{jacksonPackage}}.databind.DatabindException; +import {{jacksonPackage}}.databind.SerializationContext; +{{/useJackson3}} +{{/isJackson}} + +{{#isJsonb}} +{{! additional_properties.mustache annotates its holder field with @JsonbTransient, so the + import has to be here too - a pojo gets it from pojo.mustache, a composed model does not. }} +import jakarta.json.bind.annotation.JsonbTransient; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; +{{/isJsonb}} +{{! java.io.IOException, java.util.ArrayList, java.util.HashMap, java.util.List and + java.util.Map are contributed via model.imports by JavaClientCodegen.fromModel, which is + also where codegen imports them for container properties. Emitting them here as well + produced duplicate import lines. The rest have no Java importMapping entry and are not + duplicated, so they stay. }} +{{^isJackson}} +import java.lang.reflect.Type; +{{/isJackson}} +{{^isJsonb}} +import java.util.logging.Level; +{{/isJsonb}} +import java.util.logging.Logger; +{{#isJackson}} +import java.util.Collections; +{{/isJackson}} +import java.util.HashSet; +{{! java.util.Objects is already imported by model.mustache for every model it renders. }} +{{#supportUrlQuery}} +import java.util.StringJoiner; +{{/supportUrlQuery}} + +import {{invokerPackage}}.JSON; + +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} +{{#isJackson}} +@JsonDeserialize(using = {{classname}}.{{classname}}Deserializer.class) +@JsonSerialize(using = {{classname}}.{{classname}}Serializer.class) +{{/isJackson}} +{{#isJsonb}} +@JsonbTypeDeserializer({{classname}}.{{classname}}Deserializer.class) +@JsonbTypeSerializer({{classname}}.{{classname}}Serializer.class) +{{/isJsonb}} +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { + private static final Logger log = Logger.getLogger({{classname}}.class.getName()); + +{{>additional_properties}} + {{#isAdditionalPropertiesTrue}} + {{#isGson}} + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties({{classname}} instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched anyOf schema. + */ + private static void writeUnconsumedProperties({{classname}} value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + {{/isGson}} + {{#isJackson}} + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties({{classname}} instance, JsonNode tree) { + if (tree == null || !tree.isObject() || instance.getActualInstance() == null) { + return; + } + JsonNode consumed = JSON.getMapper().valueToTree(instance.getActualInstance()); + if (consumed == null || !consumed.isObject()) { + return; + } + java.util.Iterator> fields = tree.{{^useJackson3}}fields{{/useJackson3}}{{#useJackson3}}properties{{/useJackson3}}(){{#useJackson3}}.iterator(){{/useJackson3}}; + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + if (consumed.has(entry.getKey())) { + continue; + } + instance.putAdditionalProperty(entry.getKey(), + JSON.getMapper().convertValue(entry.getValue(), Object.class)); + } + } + {{/isJackson}} + {{/isAdditionalPropertiesTrue}} + + {{#isGson}} + /** + * 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 {{classname}} + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + {{#composedSchemas}} + {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + try { + // validate the JSON object to see if any exception is thrown + {{#isModel}} + {{#hasChildren}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/hasChildren}} + {{^hasChildren}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isMap}} + {{^isMap}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isMap}} + {{/isArray}} + {{/hasChildren}} + {{/isModel}} + {{^isModel}} + {{#isNumber}} + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isNumber}} + {{^isNumber}} + {{#isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#isNumber}} + if (!element.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type Number in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#isNumber}} + if (!entry.getValue().getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type Number in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!entry.getValue().getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isMap}} + {{^isMap}} + {{^isAnyType}} + if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isAnyType}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(element); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(element.getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!element.isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected array items to be a primitive type in the JSON string but got `%s`", element.toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(entry.getValue()); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(entry.getValue().getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!entry.getValue().isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected map values to be a primitive type in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isMap}} + {{^isMap}} + {{#isUuid}} + UUID.fromString(jsonElement.getAsString()); + {{/isUuid}} + {{^isUuid}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isUuid}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{/isNumber}} + {{/isModel}} + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage())); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/anyOf}} + {{/composedSchemas}} + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for {{classname}}: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!{{classname}}.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes '{{classname}}' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + {{#composedSchemas}} + {{#anyOf}} + {{^isArray}} + {{^vendorExtensions.x-duplicated-data-type}} + final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = gson.getDelegateAdapter(this, TypeToken.get({{{dataType}}}.class)); + {{/vendorExtensions.x-duplicated-data-type}} + {{/isArray}} + {{#isArray}} + final Type typeInstance{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = new TypeToken<{{{dataType}}}>(){}.getType(); + final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = (TypeAdapter<{{{dataType}}}>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}})); + {{/isArray}} + {{/anyOf}} + {{/composedSchemas}} + + return (TypeAdapter) new TypeAdapter<{{classname}}>() { + @Override + public void write(JsonWriter out, {{classname}} value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + {{#composedSchemas}} + {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // check if the actual instance is of the type `{{{dataType}}}` + if (value.getActualInstance() instanceof {{#isArray}}List{{/isArray}}{{#isMap}}Map{{/isMap}}{{^isMap}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isMap}}) { + element = adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}}.toJsonTree(({{{dataType}}})value.getActualInstance()); + } + {{/vendorExtensions.x-duplicated-data-type}} + {{/anyOf}} + {{/composedSchemas}} + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}"); + } + + {{#isAdditionalPropertiesTrue}} + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + {{/isAdditionalPropertiesTrue}} + elementAdapter.write(out, element); + } + + @Override + public {{classname}} read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + // non-object payloads can still match a non-object anyOf schema below + if (jsonElement.isJsonObject()) { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + JsonElement discriminatorElement = jsonObject.get("{{{propertyBaseName}}}"); + + // use discriminator value for faster anyOf lookup + {{classname}} new{{classname}} = new {{classname}}(); + if (discriminatorElement == null || !discriminatorElement.isJsonPrimitive()) { + log.log(Level.WARNING, "Failed to lookup discriminator value for {{classname}} as `{{{propertyBaseName}}}` is missing or is not a primitive type in the payload."); + } else { + // look up the discriminator value in the field `{{{propertyBaseName}}}` + switch (discriminatorElement.getAsString()) { + {{#mappedModels}} + case "{{{mappingName}}}": + deserialized = adapter{{#sanitizeDataType}}{{{modelName}}}{{/sanitizeDataType}}.fromJsonTree(jsonObject); + new{{classname}}.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(new{{classname}}, jsonElement, gson); + {{/isAdditionalPropertiesTrue}} + return new{{classname}}; + {{/mappedModels}} + default: + log.log(Level.WARNING, String.format(java.util.Locale.ROOT, "Failed to lookup discriminator value `%s` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorElement.getAsString())); + } + } + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + {{#composedSchemas}} + {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // deserialize {{{dataType}}} + try { + // validate the JSON object to see if any exception is thrown + {{#isModel}} + {{#hasChildren}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/hasChildren}} + {{^hasChildren}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isMap}} + {{^isMap}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isMap}} + {{/isArray}} + {{/hasChildren}} + {{/isModel}} + {{^isModel}} + {{#isNumber}} + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isNumber}} + {{^isNumber}} + {{#isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#isNumber}} + if (!element.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type Number in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#isNumber}} + if (!entry.getValue().getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type Number in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!entry.getValue().getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isMap}} + {{^isMap}} + {{^isAnyType}} + if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isAnyType}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(element); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(element.getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!element.isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected array items to be a primitive type in the JSON string but got `%s`", element.toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(entry.getValue()); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(entry.getValue().getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!entry.getValue().isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected map values to be a primitive type in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isMap}} + {{^isMap}} + {{#isUuid}} + UUID.fromString(jsonElement.getAsString()); + {{/isUuid}} + {{^isUuid}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isUuid}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{/isNumber}} + {{/isModel}} + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}}.fromJsonTree(jsonElement)); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(ret, jsonElement, gson); + {{/isAdditionalPropertiesTrue}} + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/anyOf}} + {{/composedSchemas}} + + throw new IOException(String.format("Failed deserialization for {{classname}}: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + {{/isGson}} + + {{#isJackson}} + public static class {{classname}}Serializer extends StdSerializer<{{classname}}> { + public {{classname}}Serializer(Class<{{classname}}> t) { + super(t); + } + + public {{classname}}Serializer() { + this(null); + } + + @Override + public void serialize({{classname}} value, JsonGenerator jgen, {{^useJackson3}}SerializerProvider provider{{/useJackson3}}{{#useJackson3}}SerializationContext serializationContext{{/useJackson3}}) throws {{^useJackson3}}IOException{{/useJackson3}}{{#useJackson3}}JacksonException{{/useJackson3}} { + {{#isAdditionalPropertiesTrue}} + {{! @JsonAnyGetter is ignored on a class with a custom serializer, so the unconsumed + properties have to be merged into the child's tree by hand. }} + if (value.getActualInstance() != null && value.getAdditionalProperties() != null + && !value.getAdditionalProperties().isEmpty()) { + JsonNode node = JSON.getMapper().valueToTree(value.getActualInstance()); + if (node != null && node.isObject()) { + {{jacksonPackage}}.databind.node.ObjectNode objectNode = ({{jacksonPackage}}.databind.node.ObjectNode) node; + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (objectNode.has(entry.getKey())) { + // the child schema owns this property + continue; + } + objectNode.set(entry.getKey(), JSON.getMapper().valueToTree(entry.getValue())); + } + {{^useJackson3}} + jgen.writeTree(node); + {{/useJackson3}} + {{#useJackson3}} + serializationContext.writeValue(jgen, node); + {{/useJackson3}} + return; + } + } + {{/isAdditionalPropertiesTrue}} + {{^useJackson3}} + jgen.writeObject(value.getActualInstance()); + {{/useJackson3}} + {{#useJackson3}} + serializationContext.writeValue(jgen, value.getActualInstance()); + {{/useJackson3}} + } + } + + public static class {{classname}}Deserializer extends StdDeserializer<{{classname}}> { + public {{classname}}Deserializer() { + this({{classname}}.class); + } + + public {{classname}}Deserializer(Class vc) { + super(vc); + } + + @Override + public {{classname}} deserialize(JsonParser jp, DeserializationContext ctxt) throws {{^useJackson3}}IOException{{/useJackson3}}{{#useJackson3}}JacksonException{{/useJackson3}} { + JsonNode tree = ctxt.readTree(jp); + Object deserialized = null; + {{#discriminator}} + Class cls = JSON.getClassForElement(tree, new {{classname}}().getClass()); + if (cls != null) { + {{^useJackson3}} + deserialized = tree.traverse(jp.getCodec()).readValueAs(cls); + {{/useJackson3}} + {{#useJackson3}} + deserialized = ctxt.readTreeAsValue(tree, ctxt.constructType(cls)); + {{/useJackson3}} + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(ret, tree); + {{/isAdditionalPropertiesTrue}} + return ret; + } + {{/discriminator}} + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // deserialize {{{dataType}}} + try { + {{^useJackson3}} + deserialized = tree.traverse(jp.getCodec()).readValueAs(new TypeReference<{{{dataType}}}>() {}); + {{/useJackson3}} + {{#useJackson3}} + deserialized = ctxt.readTreeAsValue(tree, ctxt.getTypeFactory().constructType(new TypeReference<{{{dataType}}}>() {})); + {{/useJackson3}} + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(ret, tree); + {{/isAdditionalPropertiesTrue}} + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + {{^useJackson3}} + throw new IOException(String.format(java.util.Locale.ROOT, "Failed deserialization for {{classname}}: no match found")); + {{/useJackson3}} + {{#useJackson3}} + throw DatabindException.from(jp, String.format(java.util.Locale.ROOT, "Failed deserialization for {{classname}}: no match found")); + {{/useJackson3}} + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + {{^useJackson3}} + public {{classname}} getNullValue(DeserializationContext ctxt) throws JsonMappingException { + {{/useJackson3}} + {{#useJackson3}} + public {{classname}} getNullValue(DeserializationContext ctxt) { + {{/useJackson3}} + {{#isNullable}} + return null; + {{/isNullable}} + {{^isNullable}} + {{^useJackson3}} + throw new JsonMappingException(ctxt.getParser(), "{{classname}} cannot be null"); + {{/useJackson3}} + {{#useJackson3}} + throw DatabindException.from(ctxt.getParser(), "{{classname}} cannot be null"); + {{/useJackson3}} + {{/isNullable}} + } + } + {{/isJackson}} + + {{#isJsonb}} + public static class {{classname}}Serializer implements JsonbSerializer<{{classname}}> { + @Override + public void serialize({{classname}} obj, JsonGenerator generator, SerializationContext ctx) { + if (obj.getActualInstance() == null) { + generator.writeNull(); + return; + } + {{#isAdditionalPropertiesTrue}} + if (obj.getAdditionalProperties() != null && !obj.getAdditionalProperties().isEmpty()) { + JsonObject childObject = toJsonObject(obj.getActualInstance()); + if (childObject != null) { + jakarta.json.JsonObjectBuilder builder = jakarta.json.Json.createObjectBuilder(childObject); + for (Map.Entry entry : obj.getAdditionalProperties().entrySet()) { + if (childObject.containsKey(entry.getKey())) { + // the child schema owns this property + continue; + } + builder.add(entry.getKey(), toJsonValue(entry.getValue())); + } + ctx.serialize(builder.build(), generator); + return; + } + } + {{/isAdditionalPropertiesTrue}} + ctx.serialize(obj.getActualInstance(), generator); + } + } + {{#isAdditionalPropertiesTrue}} + + /** + * Render a value through JSON-B and read it back as a JsonObject, or null if it is not an object. + */ + private static JsonObject toJsonObject(Object value) { + try (jakarta.json.JsonReader reader = jakarta.json.Json.createReader( + new java.io.StringReader(JSON.getJsonb().toJson(value)))) { + jakarta.json.JsonStructure structure = reader.read(); + return structure instanceof JsonObject ? (JsonObject) structure : null; + } catch (Exception e) { + return null; + } + } + + private static jakarta.json.JsonValue toJsonValue(Object value) { + if (value == null) { + return jakarta.json.JsonValue.NULL; + } + try (jakarta.json.JsonReader reader = jakarta.json.Json.createReader( + new java.io.StringReader(JSON.getJsonb().toJson(value)))) { + return reader.readValue(); + } + } + + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties({{classname}} instance, JsonObject jsonObject) { + if (jsonObject == null || instance.getActualInstance() == null) { + return; + } + JsonObject consumed = toJsonObject(instance.getActualInstance()); + if (consumed == null) { + return; + } + for (Map.Entry entry : jsonObject.entrySet()) { + if (consumed.containsKey(entry.getKey())) { + continue; + } + instance.putAdditionalProperty(entry.getKey(), fromJsonValue(entry.getValue())); + } + } + + private static Object fromJsonValue(jakarta.json.JsonValue value) { + switch (value.getValueType()) { + case STRING: + return ((jakarta.json.JsonString) value).getString(); + case NUMBER: + return ((jakarta.json.JsonNumber) value).numberValue(); + case TRUE: + return Boolean.TRUE; + case FALSE: + return Boolean.FALSE; + case NULL: + return null; + default: + return JSON.getJsonb().fromJson(value.toString(), + value.getValueType() == jakarta.json.JsonValue.ValueType.ARRAY + ? List.class : HashMap.class); + } + } + {{/isAdditionalPropertiesTrue}} + + {{! The DeserializationContext handed to a JsonbDeserializer belongs to the parse that is + already running: Yasson wraps whatever parser reaches ctx.deserialize in a YassonParser + whose scope bookkeeping is taken from the context, not from that parser. Handing it a + second, freshly created parser therefore produces a wrapper that believes it already + sits at the end of the outer value, so the branch's own deserializer fails in + getObject()/getValue() with NoSuchElementException or an NPE - and once one attempt has + left those counters askew a later branch binds whatever it is handed. Bind the branch + through the binding API instead, which runs a parse of its own. }} + private static Object deserializeBranch(Class type, JsonValue value) { + if (!branchAcceptsValueType(type, value)) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, + "Expected the JSON value to bind as %s but got `%s`", type.getSimpleName(), value)); + } + {{! getJsonb(), not getPlainJsonb(): a branch can itself be a discriminated-hierarchy + root, and the concrete-subtype dispatch for those lives in a deserializer that only + the main instance carries. Binding a branch never re-enters this wrapper, so there + is no recursion to break by dropping to the plain instance. }} + return JSON.getJsonb().fromJson(value.toString(), type); + } + + {{! Yasson binds by coercion, so a branch whose Java type has nothing to do with the JSON + value at hand still "matches": String swallows a number or a boolean and a numeric type + swallows a numeric string, which leaves a composed schema of scalars permanently + ambiguous. Gate on the JSON value type first - the Gson branch of this template does + the same thing through its generated per-branch validateJsonElement checks. }} + private static boolean branchAcceptsValueType(Class type, JsonValue value) { + if (type == Object.class) { + // an 'any type' branch takes whatever it is handed + return true; + } + if (AbstractOpenApiSchema.class.isAssignableFrom(type)) { + // a branch that is itself a composed schema decides for itself which JSON shapes + // it accepts - an anyOf of scalars nested inside another composed schema binds a + // scalar here + return true; + } + boolean sequence = java.util.Collection.class.isAssignableFrom(type) + || (type.isArray() && type != byte[].class); + switch (value.getValueType()) { + case ARRAY: + return sequence; + case OBJECT: + return !sequence && !bindsFromJsonScalar(type); + case TRUE: + case FALSE: + return type == Boolean.class || type == boolean.class; + case NUMBER: + return Number.class.isAssignableFrom(type) + || (type.isPrimitive() && type != boolean.class && type != char.class); + case STRING: + return !sequence + && !Number.class.isAssignableFrom(type) + && type != Boolean.class && type != boolean.class; + default: + return true; + } + } + + /** + * Whether a branch of this type binds from a JSON scalar rather than from a JSON object. + */ + private static boolean bindsFromJsonScalar(Class type) { + {{! byte[] is a scalar here on purpose: 'format: byte' arrives as a base64 string. }} + return type.isPrimitive() + || Number.class.isAssignableFrom(type) + || type == Boolean.class + || type == Character.class + || CharSequence.class.isAssignableFrom(type) + || type == java.util.UUID.class + || type == byte[].class + || type.isEnum(); + } + + public static class {{classname}}Deserializer implements JsonbDeserializer<{{classname}}> { + @Override + public {{classname}} deserialize(JsonParser parser, DeserializationContext ctx, Type rt) { + {{! A composed branch can be an array or a scalar, not only an object, and + parser.getObject() throws IllegalStateException on START_ARRAY. Read the + generic JsonValue and narrow only for the object-shaped paths below. }} + JsonValue jsonValue = parser.getValue(); + {{! Yasson routes a JSON null through this deserializer instead of short-circuiting + it, and every branch then fails to bind. Mirror the Jackson branch's + getNullValue: a nullable composed schema yields null, a non-nullable one is an + error. }} + if (jsonValue == null || jsonValue.getValueType() == JsonValue.ValueType.NULL) { + {{#isNullable}} + return null; + {{/isNullable}} + {{^isNullable}} + throw new RuntimeException("{{classname}} cannot be null"); + {{/isNullable}} + } + JsonObject jsonObject = jsonValue instanceof JsonObject ? (JsonObject) jsonValue : null; + Object deserialized = null; + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + if (jsonObject != null && jsonObject.containsKey("{{{propertyBaseName}}}")) { + String discriminatorValue = jsonObject.getString("{{{propertyBaseName}}}"); + {{#mappedModels}} + if ("{{{mappingName}}}".equals(discriminatorValue)) { + deserialized = deserializeBranch({{{modelName}}}.class, jsonValue); + {{classname}} new{{classname}} = new {{classname}}(); + new{{classname}}.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + if (jsonObject != null) { + collectUnconsumedProperties(new{{classname}}, jsonObject); + } + {{/isAdditionalPropertiesTrue}} + return new{{classname}}; + } + {{/mappedModels}} + } + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + int match = 0; + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // deserialize {{{dataType}}} + try { + deserialized = deserializeBranch({{{baseType}}}.class, jsonValue); + match++; + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + if (jsonObject != null) { + collectUnconsumedProperties(ret, jsonObject); + } + {{/isAdditionalPropertiesTrue}} + return ret; + } catch (Exception e) { + // deserialization failed, continue + } + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + if (match > 0) { + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + if (jsonObject != null) { + collectUnconsumedProperties(ret, jsonObject); + } + {{/isAdditionalPropertiesTrue}} + return ret; + } + throw new RuntimeException(String.format(java.util.Locale.ROOT, "Failed deserialization for {{classname}}: no match found")); + } + } + {{/isJsonb}} + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public {{classname}}() { + super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + } + + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + public {{classname}}({{{dataType}}} o) { + super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + setActualInstance(o); + } + {{/vendorExtensions.x-duplicated-data-type}} + + {{/composedSchemas.anyOf}} + static { + {{#composedSchemas.anyOf}} + schemas.put("{{{dataType}}}", {{{baseType}}}.class); + {{/composedSchemas.anyOf}} + {{#isJackson}} + JSON.registerDescendants({{classname}}.class, Collections.unmodifiableMap(schemas)); + {{#discriminator}} + // Initialize and register the discriminator mappings. + Map> mappings = new HashMap>(); + {{#mappedModels}} + mappings.put("{{mappingName}}", {{modelName}}.class); + {{/mappedModels}} + mappings.put("{{name}}", {{classname}}.class); + JSON.registerDiscriminator({{classname}}.class, "{{propertyBaseName}}", mappings); + {{/discriminator}} + {{/isJackson}} + } + + @Override + public Map> getSchemas() { + return {{classname}}.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}} + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + {{#isNullable}} + if (instance == null) { + super.setActualInstance(instance); + return; + } + + {{/isNullable}} + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if (JSON.isInstanceOf({{{baseType}}}.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + throw new RuntimeException("Invalid instance type. Must be {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}"); + } + + /** + * Get the actual instance, which can be the following: + * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}} + * + * @return The actual instance ({{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type-ignoring-erasure}} + /** + * Get the actual instance of `{{{dataType}}}`. If the actual instance is not `{{{dataType}}}`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `{{{dataType}}}` + * @throws ClassCastException if the instance is not `{{{dataType}}}` + */ + @SuppressWarnings("unchecked") + public {{{dataType}}} get{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}}() throws ClassCastException { + return ({{{dataType}}})super.getActualInstance(); + } + + {{/vendorExtensions.x-duplicated-data-type-ignoring-erasure}} + {{/composedSchemas.anyOf}} + +{{#supportUrlQuery}} + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + {{#composedSchemas.anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if (getActualInstance() instanceof {{{dataType}}}) { + {{#isArray}} + {{#items.isPrimitiveType}} + {{#uniqueItems}} + if (getActualInstance() != null) { + int i = 0; + for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf(_item)))); + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if (getActualInstance() != null) { + for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf((({{{dataType}}})getActualInstance()).get(i))))); + } + } + {{/uniqueItems}} + {{/items.isPrimitiveType}} + {{^items.isPrimitiveType}} + {{#items.isModel}} + {{#uniqueItems}} + if (getActualInstance() != null) { + int i = 0; + for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) { + if (_item != null) { + joiner.add(_item.toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if (getActualInstance() != null) { + for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) { + if ((({{{dataType}}})getActualInstance()).get(i) != null) { + joiner.add((({{{dataType}}})getActualInstance()).get(i).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{^items.isModel}} + {{#uniqueItems}} + if (getActualInstance() != null) { + int i = 0; + for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) { + if (_item != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf(_item)))); + } + i++; + } + } + {{/uniqueItems}} + {{^uniqueItems}} + if (getActualInstance() != null) { + for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) { + if (getActualInstance().get(i) != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf((({{{dataType}}})getActualInstance()).get(i))))); + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{/items.isPrimitiveType}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + {{#items.isPrimitiveType}} + if (getActualInstance() != null) { + for (String _key : (({{{dataType}}})getActualInstance()).keySet()) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix), + getActualInstance().get(_key), ApiClient.urlEncode(String.valueOf((({{{dataType}}})getActualInstance()).get(_key))))); + } + } + {{/items.isPrimitiveType}} + {{^items.isPrimitiveType}} + if (getActualInstance() != null) { + for (String _key : (({{{dataType}}})getActualInstance()).keySet()) { + if ((({{{dataType}}})getActualInstance()).get(_key) != null) { + joiner.add((({{{items.dataType}}})getActualInstance()).get(_key).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix)))); + } + } + } + {{/items.isPrimitiveType}} + {{/isMap}} + {{^isMap}} + {{#isPrimitiveType}} + if (getActualInstance() != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, ApiClient.urlEncode(String.valueOf(getActualInstance())))); + } + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isModel}} + if (getActualInstance() != null) { + joiner.add((({{{dataType}}})getActualInstance()).toUrlQueryString(prefix + "{{{baseName}}}" + suffix)); + } + {{/isModel}} + {{^isModel}} + if (getActualInstance() != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, ApiClient.urlEncode(String.valueOf(getActualInstance())))); + } + {{/isModel}} + {{/isPrimitiveType}} + {{/isMap}} + {{/isArray}} + return joiner.toString(); + } + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.anyOf}} + return null; + } +{{/supportUrlQuery}} + +{{#isGson}} + /** + * Create an instance of {{classname}} given an JSON string + * + * @param jsonString JSON string + * @return An instance of {{classname}} + * @throws IOException if the JSON string is invalid with respect to {{classname}} + */ + public static {{{classname}}} fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, {{{classname}}}.class); + } + + /** + * Convert an instance of {{classname}} to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +{{/isGson}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api.mustache new file mode 100644 index 000000000000..503b54a86be8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api.mustache @@ -0,0 +1,638 @@ +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiCallback; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiException; +{{#dynamicOperations}} +import {{invokerPackage}}.ApiOperation; +{{/dynamicOperations}} +import {{invokerPackage}}.ApiResponse; +{{#isJsonb}} +import {{invokerPackage}}.JSON; +{{/isJsonb}} +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; +{{#performBeanValidation}} +import {{invokerPackage}}.BeanValidationException; +{{/performBeanValidation}} + +{{#isGson}} +import com.google.gson.reflect.TypeToken; +{{/isGson}} +{{#isJackson}} +import {{jacksonPackage}}.core.type.TypeReference; +{{/isJackson}} +{{#dynamicOperations}} +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.parameters.Parameter; +{{/dynamicOperations}} + + +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} +{{#performBeanValidation}} +import {{javaxPackage}}.validation.ConstraintViolation; +import {{javaxPackage}}.validation.Validation; +import {{javaxPackage}}.validation.ValidatorFactory; +import {{javaxPackage}}.validation.executable.ExecutableValidator; +import java.util.Set; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +{{/performBeanValidation}} + +{{#imports}}import {{import}}; +{{/imports}} + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{#supportStreaming}} +import java.io.InputStream; +{{/supportStreaming}} + +{{#operations}} +public class {{classname}} { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + {{#operation}} + {{^vendorExtensions.x-group-parameters}}/** + * Build call for {{operationId}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{#lambda.escapeJavaDoc}}{{.}}{{/lambda.escapeJavaDoc}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}} + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{>nullableArgument}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { {{#servers}}"{{{url}}}"{{^-last}}, {{/-last}}{{/servers}} }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + + // create path and map variables + {{^dynamicOperations}} + String localVarPath = "{{{path}}}"{{#pathParams}} + .replace("{" + "{{baseName}}" + "}", localVarApiClient.escapeString({{#collectionFormat}}localVarApiClient.collectionPathParameterToString("{{{collectionFormat}}}", {{{paramName}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}.toString(){{/collectionFormat}})){{/pathParams}}; + {{/dynamicOperations}} + {{#dynamicOperations}} + ApiOperation apiOperation = localVarApiClient.getOperationLookupMap().get("{{{operationId}}}"); + if (apiOperation == null) { + throw new ApiException("Operation not found in OAS"); + } + Operation operation = apiOperation.getOperation(); + String localVarPath = apiOperation.getPath(); + Map paramMap = new HashMap<>(); + {{#allParams}} + {{^isFormParam}} + {{^isBodyParam}} + paramMap.put("{{baseName}}", {{paramName}}); + {{/isBodyParam}} + {{/isFormParam}} + {{/allParams}} + {{/dynamicOperations}} + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + {{#formParams}} + if ({{paramName}} != null) { + localVarFormParams.put("{{baseName}}", {{paramName}}); + } + + {{/formParams}} + {{^dynamicOperations}} + {{#queryParams}} + if ({{paramName}} != null) { + {{#isFreeFormObject}}localVarQueryParams.addAll(localVarApiClient.freeFormParameterToPairs({{paramName}}));{{/isFreeFormObject}}{{^isFreeFormObject}}{{#collectionFormat}}localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("{{{.}}}", {{/collectionFormat}}{{^collectionFormat}}localVarQueryParams.addAll(localVarApiClient.parameterToPair({{/collectionFormat}}"{{baseName}}", {{paramName}}));{{/isFreeFormObject}} + } + + {{/queryParams}} + {{#constantParams}} + {{#isQueryParam}} + // Set client side default value of Query Param "{{baseName}}". + localVarCollectionQueryParams.add(new Pair("{{baseName}}", {{#_enum}}"{{{.}}}"{{/_enum}})); + + {{/isQueryParam}} + {{/constantParams}} + {{#constantParams}} + {{#isHeaderParam}} + // Set client side default value of Header Param "{{baseName}}". + localVarHeaderParams.put("{{baseName}}", {{#_enum}}"{{{.}}}"{{/_enum}}); + + {{/isHeaderParam}} + {{/constantParams}} + {{#cookieParams}} + if ({{paramName}} != null) { + localVarCookieParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}})); + } + + {{/cookieParams}} + {{#constantParams}} + {{#isCookieParam}} + // Set client side default value of Cookie Param "{{baseName}}". + localVarCookieParams.put("{{baseName}}", {{#_enum}}"{{{.}}}"{{/_enum}}); + + {{/isCookieParam}} + {{/constantParams}} + {{/dynamicOperations}} + {{#dynamicOperations}} + localVarPath = localVarApiClient.fillParametersFromOperation(operation, paramMap, localVarPath, localVarQueryParams, localVarCollectionQueryParams, localVarHeaderParams, localVarCookieParams); + + {{/dynamicOperations}} + final String[] localVarAccepts = { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + {{^dynamicOperations}} + {{#headerParams}} + + if ({{paramName}} != null) { + {{#headerIsJsonMimeType}} + localVarHeaderParams.put("{{baseName}}", localVarApiClient.parameterToJsonString({{paramName}})); + {{/headerIsJsonMimeType}} + {{^headerIsJsonMimeType}} + localVarHeaderParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}})); + {{/headerIsJsonMimeType}} + } + + {{/headerParams}} + {{/dynamicOperations}} + + String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{#-last}}{{#withAWSV4Signature}}, {{/withAWSV4Signature}}{{/-last}}{{/authMethods}}{{#withAWSV4Signature}}"AWS4Auth"{{/withAWSV4Signature}} }; + return localVarApiClient.buildCall(basePath, localVarPath, {{^dynamicOperations}}"{{httpMethod}}"{{/dynamicOperations}}{{#dynamicOperations}}apiOperation.getMethod(){{/dynamicOperations}}, localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + @SuppressWarnings("rawtypes") + private okhttp3.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{>nullableArgument}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException { + {{! The required-parameter checks are deliberately NOT guarded by performBeanValidation. + They used to live inside the inverted performBeanValidation section, so enabling + bean validation REMOVED them and substituted a validator that never fires for a + plain null argument - turning a clear ApiException into a NullPointerException + further down, or letting the null reach the server. Bean validation is additive + on top of these checks, never a replacement. }} + {{#allParams}} + {{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); + } + + {{/required}} + {{/allParams}} + {{^performBeanValidation}} + return {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback); + + {{/performBeanValidation}} + {{#performBeanValidation}} + try { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + ExecutableValidator executableValidator = factory.getValidator().forExecutables(); + + Object[] parameterValues = { {{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}} }; + Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isArray}}java.util.List{{/isArray}}{{#isMap}}java.util.Map{{/isMap}}{{^isArray}}{{^isMap}}{{{dataType}}}{{/isMap}}{{/isArray}}.class{{/allParams}}); + Set> violations = executableValidator.validateParameters(this, method, + parameterValues); + + if (violations.size() == 0) { + return {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback); + } else { + throw new BeanValidationException((Set) violations); + } + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } catch (SecurityException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } + {{/performBeanValidation}} + } + + {{^vendorExtensions.x-group-parameters}} + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{#lambda.escapeJavaDoc}}{{.}}{{/lambda.escapeJavaDoc}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}}{{#returnType}} + * @return {{.}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + {{#vendorExtensions.x-streaming}} + public {{#returnType}}InputStream {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{>nullableArgument}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + {{#returnType}}InputStream localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + return localVarResp;{{/returnType}} + } + {{/vendorExtensions.x-streaming}} + {{^vendorExtensions.x-streaming}} + public {{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{>nullableArgument}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{.}}}> localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + return localVarResp.getData();{{/returnType}} + } + {{/vendorExtensions.x-streaming}} + {{/vendorExtensions.x-group-parameters}} + + {{^vendorExtensions.x-group-parameters}}/** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{#lambda.escapeJavaDoc}}{{.}}{{/lambda.escapeJavaDoc}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}} + * @return ApiResponse<{{returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-streaming}} InputStream {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{>nullable_var_annotations}} {{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null); + {{#returnType}} + {{#errorObjectType}} + try { + {{#isGson}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();{{/isGson}} + {{#isJackson}}Type localVarReturnType = new TypeReference<{{{returnType}}}>(){}.getType();{{/isJackson}} + {{#isJsonb}}Type localVarReturnType = new JSON.GenericType<{{{returnType}}}>(){}.getType();{{/isJsonb}} + return localVarApiClient.executeStream(localVarCall, localVarReturnType); + } catch (ApiException e) { + {{#isGson}}e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<{{{errorObjectType}}}>(){}.getType()));{{/isGson}} + {{#isJackson}}e.setErrorObject(localVarApiClient.getJSON().deserialize(e.getResponseBody(), new TypeReference<{{{errorObjectType}}}>(){}.getType()));{{/isJackson}} + {{#isJsonb}}e.setErrorObject(localVarApiClient.getJSON().deserialize(e.getResponseBody(), new JSON.GenericType<{{{errorObjectType}}}>(){}.getType()));{{/isJsonb}} + throw e; + } + {{/errorObjectType}} + {{^errorObjectType}} + {{#isGson}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();{{/isGson}} + {{#isJackson}}Type localVarReturnType = new TypeReference<{{{returnType}}}>(){}.getType();{{/isJackson}} + {{#isJsonb}}Type localVarReturnType = new JSON.GenericType<{{{returnType}}}>(){}.getType();{{/isJsonb}} + return localVarApiClient.executeStream(localVarCall, localVarReturnType); + {{/errorObjectType}} + {{/returnType}} + } + {{/vendorExtensions.x-streaming}}{{^vendorExtensions.x-streaming}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{>nullableArgument}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null); + {{^returnType}} + return localVarApiClient.execute(localVarCall); + {{/returnType}} + {{#returnType}} + {{#errorObjectType}} + try { + {{#isGson}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();{{/isGson}} + {{#isJackson}}Type localVarReturnType = new TypeReference<{{{returnType}}}>(){}.getType();{{/isJackson}} + {{#isJsonb}}Type localVarReturnType = new JSON.GenericType<{{{returnType}}}>(){}.getType();{{/isJsonb}} + return localVarApiClient.execute(localVarCall, localVarReturnType); + } catch (ApiException e) { + {{#isGson}}e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<{{{errorObjectType}}}>(){}.getType()));{{/isGson}} + {{#isJackson}}e.setErrorObject(localVarApiClient.getJSON().deserialize(e.getResponseBody(), new TypeReference<{{{errorObjectType}}}>(){}.getType()));{{/isJackson}} + {{#isJsonb}}e.setErrorObject(localVarApiClient.getJSON().deserialize(e.getResponseBody(), new JSON.GenericType<{{{errorObjectType}}}>(){}.getType()));{{/isJsonb}} + throw e; + } + {{/errorObjectType}} + {{^errorObjectType}} + {{#isGson}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();{{/isGson}} + {{#isJackson}}Type localVarReturnType = new TypeReference<{{{returnType}}}>(){}.getType();{{/isJackson}} + {{#isJsonb}}Type localVarReturnType = new JSON.GenericType<{{{returnType}}}>(){}.getType();{{/isJsonb}} + return localVarApiClient.execute(localVarCall, localVarReturnType); + {{/errorObjectType}} + {{/returnType}} + } + {{/vendorExtensions.x-streaming}} + + {{^vendorExtensions.x-group-parameters}}/** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{#lambda.escapeJavaDoc}}{{.}}{{/lambda.escapeJavaDoc}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}} + * @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 + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Async({{#allParams}}{{>nullableArgument}} {{paramName}}, {{/allParams}}final ApiCallback<{{{returnType}}}{{^returnType}}Void{{/returnType}}> _callback) throws ApiException { + + okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}_callback); + {{#returnType}}{{#isGson}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();{{/isGson}}{{#isJackson}}Type localVarReturnType = new TypeReference<{{{returnType}}}>(){}.getType();{{/isJackson}}{{#isJsonb}}Type localVarReturnType = new JSON.GenericType<{{{returnType}}}>(){}.getType();{{/isJsonb}} + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);{{/returnType}}{{^returnType}}localVarApiClient.executeAsync(localVarCall, _callback);{{/returnType}} + return localVarCall; + } + {{#vendorExtensions.x-group-parameters}} + + public class API{{operationId}}Request { + {{#requiredParams}} + {{>nullable_var_annotations}}{{! prevent indent}} + private final {{#lambda.jSpecifyDatatype}}{{{dataType}}}{{/lambda.jSpecifyDatatype}} {{paramName}}; + {{/requiredParams}} + {{#optionalParams}} + {{>nullable_var_annotations}}{{! prevent indent}} + private {{#lambda.jSpecifyDatatype}}{{{dataType}}}{{/lambda.jSpecifyDatatype}} {{paramName}}; + {{/optionalParams}} + + private API{{operationId}}Request({{#requiredParams}}{{>nullableArgument}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}) { + {{#requiredParams}} + this.{{paramName}} = {{paramName}}; + {{/requiredParams}} + } + + {{#optionalParams}} + /** + * Set {{paramName}} + * @param {{paramName}} {{description}} (optional{{^isContainer}}{{#defaultValue}}, default to {{#lambda.escapeJavaDoc}}{{.}}{{/lambda.escapeJavaDoc}}{{/defaultValue}}{{/isContainer}}) + * @return API{{operationId}}Request + */ + public API{{operationId}}Request {{paramName}}({{>nullableArgument}} {{paramName}}) { + this.{{paramName}} = {{paramName}}; + return this; + } + + {{/optionalParams}} + /** + * Build call for {{operationId}} + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback); + } + + /** + * Execute {{operationId}} request{{#returnType}} + * @return {{.}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + {{^vendorExtensions.x-streaming}} + public {{{returnType}}}{{^returnType}}void{{/returnType}} execute() throws ApiException { + {{#returnType}}ApiResponse<{{{.}}}> localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + return localVarResp.getData();{{/returnType}} + } + {{/vendorExtensions.x-streaming}} + {{#vendorExtensions.x-streaming}} + public InputStream execute() throws ApiException { + return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } + {{/vendorExtensions.x-streaming}} + + /** + * Execute {{operationId}} request with HTTP info returned + * @return ApiResponse<{{returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + {{^vendorExtensions.x-streaming}} + public ApiResponse<{{{returnType}}}{{^returnType}}Void{{/returnType}}> executeWithHttpInfo() throws ApiException { + return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } + {{/vendorExtensions.x-streaming}} + {{#vendorExtensions.x-streaming}} + public InputStream executeWithHttpInfo() throws ApiException { + return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } + {{/vendorExtensions.x-streaming}} + + /** + * Execute {{operationId}} request (asynchronously) + * @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 + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public okhttp3.Call executeAsync(final ApiCallback<{{{returnType}}}{{^returnType}}Void{{/returnType}}> _callback) throws ApiException { + return {{operationId}}Async({{#allParams}}{{paramName}}, {{/allParams}}_callback); + } + } + + /** + * {{summary}} + * {{notes}}{{#requiredParams}} + * @param {{paramName}} {{description}} (required){{/requiredParams}} + * @return API{{operationId}}Request + {{#responses.0}} + * @http.response.details + + + + {{#responses}} + + {{/responses}} +
Response Details
Status Code Description Response Headers
{{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}}
+ {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public API{{operationId}}Request {{operationId}}({{#requiredParams}}{{>nullable_var_annotations}} {{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}) { + return new API{{operationId}}Request({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}); + } + {{/vendorExtensions.x-group-parameters}} + {{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/apiException.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/apiException.mustache new file mode 100644 index 000000000000..96283bc054d3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/apiException.mustache @@ -0,0 +1,196 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.Map; +import java.util.List; +{{#caseInsensitiveResponseHeaders}} +import java.util.Map.Entry; +import java.util.TreeMap; +{{/caseInsensitiveResponseHeaders}} + + +/** + *

ApiException class.

+ */ +@SuppressWarnings("serial") +{{>generatedAnnotation}} + +public class ApiException extends{{#useRuntimeException}} RuntimeException {{/useRuntimeException}}{{^useRuntimeException}} Exception {{/useRuntimeException}}{ + private static final long serialVersionUID = 1L; + + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + {{#errorObjectType}} + private {{{errorObjectType}}} errorObject = null; + {{/errorObjectType}} + + /** + *

Constructor for ApiException.

+ */ + public ApiException() {} + + /** + *

Constructor for ApiException.

+ * + * @param throwable a {@link java.lang.Throwable} object + */ + public ApiException(Throwable throwable) { + super(throwable); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + */ + public ApiException(String message) { + super(message); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + {{#caseInsensitiveResponseHeaders}} + Map> headers = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : responseHeaders.entrySet()){ + headers.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}; + this.responseBody = responseBody; + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, Map> responseHeaders, String responseBody) { + this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message a {@link java.lang.String} object + */ + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message the error message + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + {{#caseInsensitiveResponseHeaders}} + Map> headers = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : responseHeaders.entrySet()){ + headers.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } + + /** + * Get the exception message including HTTP response data. + * + * @return The exception message + */ + public String getMessage() { + return String.format(java.util.Locale.ROOT, "Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", + super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders()); + } + {{#errorObjectType}} + + /** + * Get the error object. + * + * @return Error object + */ + public {{{errorObjectType}}} getErrorObject() { + return errorObject; + } + + /** + * Get the error object. + * + * @param errorObject Error object + */ + public void setErrorObject({{{errorObjectType}}} errorObject) { + this.errorObject = errorObject; + } + {{/errorObjectType}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api_doc.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api_doc.mustache new file mode 100644 index 000000000000..5d349f582593 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api_doc.mustache @@ -0,0 +1,110 @@ +# {{classname}}{{#description}} +{{.}}{{/description}} + +All URIs are relative to *{{basePath}}* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +{{#operations}}{{#operation}}| [**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} | +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{operationId}}**{{^vendorExtensions.x-group-parameters}} +> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}){{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}} +> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}.{{paramName}}({{paramName}}){{/optionalParams}}.execute();{{/vendorExtensions.x-group-parameters}} + +{{summary}}{{#notes}} + +{{.}}{{/notes}} + +### Example +```java +// Import classes: +import {{{invokerPackage}}}.ApiClient; +import {{{invokerPackage}}}.ApiException; +import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}} +import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} +import {{{modelPackage}}}.*; +import {{{package}}}.{{{classname}}}; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("{{{basePath}}}"); + {{#withAWSV4Signature}} + // Configure AWS Signature V4 authorization + defaultClient.setAWS4Configuration("YOUR_ACCESS_KEY", "YOUR_SECRET_KEY", "REGION", "SERVICE") + {{/withAWSV4Signature}} + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(defaultClient); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{{paramName}}}({{{paramName}}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}}{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------|{{/-last}}{{/allParams}} +{{#allParams}}| **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}{{^baseType}}{{#isModel}}{{dataType}}{{/isModel}}{{#isEnumRef}}{{dataType}}{{/isEnumRef}}{{/baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} | +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
{{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api_test.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api_test.mustache new file mode 100644 index 000000000000..b56bdf4db09b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/api_test.mustache @@ -0,0 +1,65 @@ +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiException; +{{#imports}}import {{import}}; +{{/imports}} +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; +{{#supportStreaming}} +import java.io.InputStream; +{{/supportStreaming}} + +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; + +{{/useBeanValidation}} +/** + * API tests for {{classname}} + */ +@Disabled +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}} + {{#operation}} + /** + {{#summary}} + * {{summary}} + * + {{/summary}} + {{#notes}} + * {{notes}} + * + {{/notes}} + * @throws ApiException if the Api call fails + */ + @Test + public void {{operationId}}Test() throws ApiException { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + {{#vendorExtensions.x-streaming}} + InputStream response = api.{{operationId}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{paramName}}({{paramName}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}} + {{/vendorExtensions.x-streaming}} + {{^vendorExtensions.x-streaming}} + {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{paramName}}({{paramName}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}} + {{/vendorExtensions.x-streaming}} + // TODO: test validations + } + + {{/operation}} + {{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/AWS4Auth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/AWS4Auth.mustache new file mode 100644 index 000000000000..d83671840a8a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/AWS4Auth.mustache @@ -0,0 +1,121 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.List; +import java.util.stream.Collectors; + +import software.amazon.awssdk.auth.credentials.AnonymousCredentialsProvider; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.AwsSessionCredentials; +import software.amazon.awssdk.auth.credentials.AwsCredentials; +import software.amazon.awssdk.auth.signer.Aws4Signer; +import software.amazon.awssdk.auth.signer.params.Aws4SignerParams; +import software.amazon.awssdk.http.ContentStreamProvider; +import software.amazon.awssdk.http.SdkHttpFullRequest; +import software.amazon.awssdk.http.SdkHttpMethod; +import software.amazon.awssdk.regions.Region; + +import okio.Buffer; + +{{>generatedAnnotation}} + +public class AWS4Auth implements Authentication { + + private AwsCredentials credentials; + private String region; + private String service; + + public AWS4Auth() { + this.credentials = AnonymousCredentialsProvider.create().resolveCredentials(); + } + + public void setCredentials(String accessKey, String secretKey) { + this.credentials = AwsBasicCredentials.create(accessKey, secretKey); + } + + public void setCredentials(String accessKey, String secretKey, String sessionToken) { + this.credentials = AwsSessionCredentials.create(accessKey, secretKey, sessionToken); + } + + public void setRegion(String region) { + this.region = region; + } + + public void setService(String service) { + this.service = service; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, + Map cookieParams, byte[] payload, String method, URI uri) + throws ApiException { + + SdkHttpFullRequest.Builder requestBuilder = + SdkHttpFullRequest.builder().uri(uri).method(SdkHttpMethod.fromValue(method)); + + // SigV4 requires every x-amz-* header that is actually sent to be part of the canonical + // request, otherwise AWS rejects the signature. Content-Type is deliberately not signed: + // OkHttp's BridgeInterceptor rewrites multipart content types to append the boundary, so the + // signed value would not match the value on the wire. + for (Map.Entry header : headerParams.entrySet()) { + if (header.getKey().toLowerCase(java.util.Locale.ROOT).startsWith("x-amz-")) { + requestBuilder.putHeader(header.getKey(), header.getValue()); + } + } + + ContentStreamProvider provider = new ContentStreamProvider() { + @Override + public InputStream newStream() { + return new ByteArrayInputStream(payload); + } + }; + + requestBuilder = requestBuilder.contentStreamProvider(provider); + + SdkHttpFullRequest signableRequest = sign(requestBuilder); + + Map headers = signableRequest.headers().entrySet().stream() + .collect(Collectors.toMap(s -> s.getKey(), e -> e.getValue().get(0))); + + headerParams.putAll(headers); + } + + /** + * AWS Signature Version 4 signing. + * + * @param request {@link SdkHttpFullRequest.Builder} + * @return {@link SdkHttpFullRequest} + * @throws ApiException if only part of the signing configuration (credentials, region, service) is set + */ + private SdkHttpFullRequest sign(final SdkHttpFullRequest.Builder request) throws ApiException { + + SdkHttpFullRequest req = request.build(); + + final boolean configured = this.service != null || this.region != null || this.credentials != null; + if (configured && (this.service == null || this.region == null || this.credentials == null)) { + // sending the request unsigned would only surface as a 403 from the server + throw new ApiException("AWS Signature V4 is configured incompletely: credentials, region and service are all required"); + } + + if (this.service != null && this.region != null && this.credentials != null) { + Aws4SignerParams params = Aws4SignerParams.builder().signingName(this.service) + .signingRegion(Region.of(this.region)).awsCredentials(this.credentials).build(); + + Aws4Signer signer = Aws4Signer.create(); + + req = signer.sign(req, params); + } + + return req; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/ApiKeyAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/ApiKeyAuth.mustache new file mode 100644 index 000000000000..31a92bfa5d80 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/ApiKeyAuth.mustache @@ -0,0 +1,70 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/Authentication.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/Authentication.mustache new file mode 100644 index 000000000000..1dee610e63f6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/Authentication.mustache @@ -0,0 +1,27 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @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 ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, byte[] payload, String method, URI uri) throws ApiException; +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/HttpBasicAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/HttpBasicAuth.mustache new file mode 100644 index 000000000000..579a8879c92c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/HttpBasicAuth.mustache @@ -0,0 +1,49 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + // UTF-8 explicitly: Credentials.basic defaults to ISO-8859-1, which turns every character + // outside Latin-1 into '?'. This matches the shared Java HttpBasicAuth template. It differs on + // purpose from okhttp-gson and retrofit2, which keep the ISO-8859-1 default, so for such + // credentials this library sends a different Authorization header than okhttp-gson does. + headerParams.put("Authorization", Credentials.basic(username == null ? "" : username, password == null ? "" : password, StandardCharsets.UTF_8)); + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/HttpBearerAuth.mustache new file mode 100644 index 000000000000..8008a0de73af --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/HttpBearerAuth.mustache @@ -0,0 +1,64 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +{{>generatedAnnotation}} + +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier == null ? null : tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token + */ + public void setBearerToken(String 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 + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/OAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/OAuth.mustache new file mode 100644 index 000000000000..d4032f6ee0f5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/OAuth.mustache @@ -0,0 +1,33 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} + +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (accessToken == null) { + return; + } + headerParams.put("Authorization", "Bearer " + accessToken); + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/RetryingOAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/RetryingOAuth.mustache new file mode 100644 index 000000000000..10cac5f184f1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/auth/RetryingOAuth.mustache @@ -0,0 +1,276 @@ +{{>licenseInfo}} + +{{#hasOAuthMethods}} +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.JSON; +import {{invokerPackage}}.Pair; + +import okhttp3.FormBody; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RetryingOAuth extends OAuth implements Interceptor { + private final OkHttpClient client; + private final TokenRequestBuilder tokenRequestBuilder; + private final JSON json; + + public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) { + this.client = client; + this.tokenRequestBuilder = tokenRequestBuilder; + this.json = new JSON(); + } + + public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) { + this(new OkHttpClient(), tokenRequestBuilder); + } + + public RetryingOAuth( + String tokenUrl, + String clientId, + OAuthFlow flow, + String clientSecret, + Map parameters + ) { + this(TokenRequestBuilder.tokenLocation(tokenUrl) + .setClientId(clientId) + .setClientSecret(clientSecret)); + setFlow(flow); + if (parameters != null) { + for (Map.Entry entry : parameters.entrySet()) { + tokenRequestBuilder.setParameter(entry.getKey(), entry.getValue()); + } + } + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case ACCESS_CODE: + tokenRequestBuilder.setGrantType("authorization_code"); + break; + case IMPLICIT: + tokenRequestBuilder.setGrantType("implicit"); + break; + case PASSWORD: + tokenRequestBuilder.setGrantType("password"); + break; + case APPLICATION: + tokenRequestBuilder.setGrantType("client_credentials"); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) throws IOException { + return retryingIntercept(chain, true); + } + + private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException { + Request request = chain.request(); + + // If the request already has an authorization (e.g. Basic auth), proceed with the request as is + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // Get the token if it has not yet been acquired + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Remember the token this request is sent with: a 401/403 must only trigger a token refresh + // if no other thread has refreshed the token in the meantime (see updateAccessToken). + String requestAccessToken = getAccessToken(); + if (requestAccessToken != null) { + // Build the request + Request.Builder requestBuilder = request.newBuilder(); + requestBuilder.header("Authorization", "Bearer " + requestAccessToken); + + // Execute the request + Response response = chain.proceed(requestBuilder.build()); + + // 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row + if ( + response != null && + ( response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || + response.code() == HttpURLConnection.HTTP_FORBIDDEN ) && + updateTokenAndRetryOnAuthorizationFailure + ) { + try { + if (updateAccessToken(requestAccessToken)) { + if (response.body() != null) { + response.body().close(); + } + return retryingIntercept(chain, false); + } + } catch (Exception e) { + if (response.body() != null) { + response.body().close(); + } + throw e; + } + } + return response; + } + else { + return chain.proceed(chain.request()); + } + } + + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + Request tokenRequest = tokenRequestBuilder.build(); + try (Response response = client.newCall(tokenRequest).execute()) { + String body = response.body().string(); + if (!response.isSuccessful()) { + // surface the token endpoint's answer instead of silently sending the request unauthenticated + throw new IOException("OAuth token request to " + tokenRequest.url() + " failed with HTTP " + + response.code() + (body.isEmpty() ? "" : ": " + body)); + } + AccessTokenResponse tokenResponse; + try { + tokenResponse = json.deserialize(body, AccessTokenResponse.class); + } catch (RuntimeException e) { + throw new IOException("OAuth token response from " + tokenRequest.url() + " could not be parsed: " + body, e); + } + if (tokenResponse == null || tokenResponse.accessToken == null) { + throw new IOException("OAuth token response from " + tokenRequest.url() + " contains no access_token: " + body); + } + setAccessToken(tokenResponse.accessToken); + } + } + return getAccessToken() == null || !getAccessToken().equals(requestAccessToken); + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + // No implementation necessary + } + + public static class AccessTokenResponse { + {{#isJackson}} + @com.fasterxml.jackson.annotation.JsonProperty("access_token") + {{/isJackson}} + {{#isGson}} + @com.google.gson.annotations.SerializedName("access_token") + {{/isGson}} + {{#isJsonb}} + @jakarta.json.bind.annotation.JsonbProperty("access_token") + {{/isJsonb}} + public String accessToken; + + {{#isJackson}} + @com.fasterxml.jackson.annotation.JsonProperty("token_type") + {{/isJackson}} + {{#isGson}} + @com.google.gson.annotations.SerializedName("token_type") + {{/isGson}} + {{#isJsonb}} + @jakarta.json.bind.annotation.JsonbProperty("token_type") + {{/isJsonb}} + public String tokenType; + + {{#isJackson}} + @com.fasterxml.jackson.annotation.JsonProperty("expires_in") + {{/isJackson}} + {{#isGson}} + @com.google.gson.annotations.SerializedName("expires_in") + {{/isGson}} + {{#isJsonb}} + @jakarta.json.bind.annotation.JsonbProperty("expires_in") + {{/isJsonb}} + public Long expiresIn; + + {{#isJackson}} + @com.fasterxml.jackson.annotation.JsonProperty("refresh_token") + {{/isJackson}} + {{#isGson}} + @com.google.gson.annotations.SerializedName("refresh_token") + {{/isGson}} + {{#isJsonb}} + @jakarta.json.bind.annotation.JsonbProperty("refresh_token") + {{/isJsonb}} + public String refreshToken; + + {{#isJackson}} + @com.fasterxml.jackson.annotation.JsonProperty("scope") + {{/isJackson}} + {{#isGson}} + @com.google.gson.annotations.SerializedName("scope") + {{/isGson}} + {{#isJsonb}} + @jakarta.json.bind.annotation.JsonbProperty("scope") + {{/isJsonb}} + public String scope; + } + + public static class TokenRequestBuilder { + private String tokenUrl; + private String clientId; + private String clientSecret; + private String grantType; + private final Map parameters = new HashMap<>(); + + public static TokenRequestBuilder tokenLocation(String tokenUrl) { + return new TokenRequestBuilder().setTokenUrl(tokenUrl); + } + + public TokenRequestBuilder setTokenUrl(String tokenUrl) { + this.tokenUrl = tokenUrl; + return this; + } + + public TokenRequestBuilder setClientId(String clientId) { + this.clientId = clientId; + return this; + } + + public TokenRequestBuilder setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + return this; + } + + public TokenRequestBuilder setGrantType(String grantType) { + this.grantType = grantType; + return this; + } + + public TokenRequestBuilder setParameter(String name, String value) { + this.parameters.put(name, value); + return this; + } + + public Request build() { + FormBody.Builder formBuilder = new FormBody.Builder(); + if (grantType != null) formBuilder.add("grant_type", grantType); + if (clientId != null) formBuilder.add("client_id", clientId); + if (clientSecret != null) formBuilder.add("client_secret", clientSecret); + for (Map.Entry entry : parameters.entrySet()) { + formBuilder.add(entry.getKey(), entry.getValue()); + } + + return new Request.Builder() + .url(tokenUrl) + .post(formBuilder.build()) + .build(); + } + } +} +{{/hasOAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/build.gradle.mustache new file mode 100644 index 000000000000..e78ed6110cab --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/build.gradle.mustache @@ -0,0 +1,156 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' +apply plugin: 'java' +apply plugin: 'maven-publish' + +group = '{{groupId}}' +version = '{{artifactVersion}}' + +repositories { + mavenCentral() +} +{{#sourceFolder}} +sourceSets { + main.java.srcDirs = ['{{sourceFolder}}'] +} + +{{/sourceFolder}} + +sourceCompatibility = {{#useJackson3}}JavaVersion.VERSION_17{{/useJackson3}}{{^useJackson3}}{{#java17}}JavaVersion.VERSION_17{{/java17}}{{^java17}}{{#java11}}JavaVersion.VERSION_11{{/java11}}{{^java11}}JavaVersion.VERSION_1_8{{/java11}}{{/java17}}{{/useJackson3}} +targetCompatibility = {{#useJackson3}}JavaVersion.VERSION_17{{/useJackson3}}{{^useJackson3}}{{#java17}}JavaVersion.VERSION_17{{/java17}}{{^java17}}{{#java11}}JavaVersion.VERSION_11{{/java11}}{{^java11}}JavaVersion.VERSION_1_8{{/java11}}{{/java17}}{{/useJackson3}} + +publishing { + publications { + maven(MavenPublication) { + artifactId = '{{artifactId}}' + from components.java + } + } +} + +task execute(type:JavaExec) { + mainClass = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} + +ext { + {{#swagger1AnnotationLibrary}} + swagger_annotations_version = "1.6.6" + {{/swagger1AnnotationLibrary}} + {{#swagger2AnnotationLibrary}} + swagger_annotations_version = "2.2.15" + {{/swagger2AnnotationLibrary}} + {{#useJakartaEe}} + jakarta_annotation_version = "2.1.1" + {{#useBeanValidation}} + bean_validation_version = "3.0.2" + {{/useBeanValidation}} + {{/useJakartaEe}} + {{^useJakartaEe}} + jakarta_annotation_version = "1.3.5" + {{#useBeanValidation}} + bean_validation_version = "2.0.2" + {{/useBeanValidation}} + {{/useJakartaEe}} + {{#isJackson}} + {{#useJackson3}} + jackson_version = "3.2.1" + {{/useJackson3}} + {{^useJackson3}} + jackson_version = "2.22.1" + {{/useJackson3}} + jackson_annotations_version = "2.22" + {{/isJackson}} + okhttp_version = "5.4.0" +} + +dependencies { + {{#swagger1AnnotationLibrary}} + implementation "io.swagger:swagger-annotations:$swagger_annotations_version" + {{/swagger1AnnotationLibrary}} + {{#swagger2AnnotationLibrary}} + implementation "io.swagger.core.v3:swagger-annotations:$swagger_annotations_version" + {{/swagger2AnnotationLibrary}} + {{^useJspecify}} + implementation "com.google.code.findbugs:jsr305:3.0.2" + {{/useJspecify}} + {{#useJspecify}} + implementation "org.jspecify:jspecify:1.0.0" + {{/useJspecify}} + implementation "com.squareup.okhttp3:okhttp:$okhttp_version" + implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version" + {{#isGson}} + implementation 'com.google.code.gson:gson:2.10.1' + implementation 'io.gsonfire:gson-fire:1.9.0' + {{/isGson}} + {{#isJackson}} + implementation "{{jacksonPackage}}.core:jackson-core:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_annotations_version" + implementation "{{jacksonPackage}}.core:jackson-databind:$jackson_version" + {{^useJackson3}} + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + {{/useJackson3}} + {{/isJackson}} + {{#openApiNullable}} + {{^isJsonb}} + implementation 'org.openapitools:jackson-databind-nullable:0.2.12' + {{/isJsonb}} + {{/openApiNullable}} + {{#isJsonb}} + implementation 'jakarta.json.bind:jakarta.json.bind-api:3.0.1' + implementation 'org.eclipse:yasson:3.0.4' + implementation 'jakarta.json:jakarta.json-api:2.1.3' + implementation 'org.eclipse.parsson:parsson:1.1.7' + {{/isJsonb}} + {{#withAWSV4Signature}} + implementation 'software.amazon.awssdk:auth:2.20.157' + {{/withAWSV4Signature}} + {{#useReflectionEqualsHashCode}} + implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.18.0' + {{/useReflectionEqualsHashCode}} + {{#joda}} + implementation 'joda-time:joda-time:2.12.0' + {{#isJackson}} + implementation "{{jacksonPackage}}.datatype:jackson-datatype-joda:$jackson_version" + {{/isJackson}} + {{/joda}} + {{#dynamicOperations}} + implementation 'io.swagger.parser.v3:swagger-parser-v3:2.0.30' + {{/dynamicOperations}} + {{#parcelableModel}} + // Needed for Parcelable support + compileOnly 'com.google.android:android:4.1.1.4' + {{/parcelableModel}} + compileOnly "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + {{#useBeanValidation}} + compileOnly "jakarta.validation:jakarta.validation-api:$bean_validation_version" + {{/useBeanValidation}} + {{#performBeanValidation}} + // Bean Validation Impl. used to perform BeanValidation + {{#useJakartaEe}} + implementation 'org.hibernate.validator:hibernate-validator:8.0.3.Final' + // Jakarta EL API + implementation, required by Hibernate Validator to interpolate constraint messages + implementation 'jakarta.el:jakarta.el-api:5.0.1' + implementation 'org.glassfish.expressly:expressly:5.0.0' + {{/useJakartaEe}} + {{^useJakartaEe}} + implementation 'org.hibernate.validator:hibernate-validator:6.2.5.Final' + // javax.el API + implementation, required by Hibernate Validator to interpolate constraint messages + implementation 'org.glassfish:jakarta.el:3.0.4' + {{/useJakartaEe}} + {{/performBeanValidation}} + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.3' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.3' +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} + +test { + useJUnitPlatform() + dependsOn 'cleanTest' + testLogging { + events "passed", "skipped", "failed" + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/build.sbt.mustache new file mode 100644 index 000000000000..5b26c05a79d9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/build.sbt.mustache @@ -0,0 +1,88 @@ +// {{#useJackson3}}Jackson 3 requires Java 17.{{/useJackson3}}{{^useJackson3}}Keep the bytecode level in sync with the Maven and Gradle builds.{{/useJackson3}} +val javaVersion = "{{#useJackson3}}17{{/useJackson3}}{{^useJackson3}}{{#java17}}17{{/java17}}{{^java17}}{{#java11}}11{{/java11}}{{^java11}}1.8{{/java11}}{{/java17}}{{/useJackson3}}" + +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.13.6", + scalacOptions ++= Seq("-feature"), + compile / javacOptions ++= Seq("-Xlint:deprecation", "-source", javaVersion, "-target", javaVersion), + Compile / packageDoc / publishArtifact := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + {{#swagger1AnnotationLibrary}} + "io.swagger" % "swagger-annotations" % "1.6.6", + {{/swagger1AnnotationLibrary}} + {{#swagger2AnnotationLibrary}} + "io.swagger.core.v3" % "swagger-annotations" % "2.2.15", + {{/swagger2AnnotationLibrary}} + {{^useJspecify}} + "com.google.code.findbugs" % "jsr305" % "3.0.2", + {{/useJspecify}} + {{#useJspecify}} + "org.jspecify" % "jspecify" % "1.0.0", + {{/useJspecify}} + "com.squareup.okhttp3" % "okhttp-jvm" % "5.4.0", + "com.squareup.okhttp3" % "logging-interceptor" % "5.4.0", + {{#isGson}} + "com.google.code.gson" % "gson" % "2.10.1", + "io.gsonfire" % "gson-fire" % "1.9.0", + {{/isGson}} + {{#isJackson}} + "{{jacksonPackage}}.core" % "jackson-core" % "{{#useJackson3}}3.2.1{{/useJackson3}}{{^useJackson3}}2.22.1{{/useJackson3}}", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.22", + "{{jacksonPackage}}.core" % "jackson-databind" % "{{#useJackson3}}3.2.1{{/useJackson3}}{{^useJackson3}}2.22.1{{/useJackson3}}", + {{^useJackson3}} + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.22.1", + {{/useJackson3}} + {{/isJackson}} + {{#openApiNullable}} + {{^isJsonb}} + "org.openapitools" % "jackson-databind-nullable" % "0.2.12", + {{/isJsonb}} + {{/openApiNullable}} + {{#isJsonb}} + "jakarta.json.bind" % "jakarta.json.bind-api" % "3.0.1", + "org.eclipse" % "yasson" % "3.0.4", + "jakarta.json" % "jakarta.json-api" % "2.1.3", + "org.eclipse.parsson" % "parsson" % "1.1.7", + {{/isJsonb}} + {{#useReflectionEqualsHashCode}} + "org.apache.commons" % "commons-lang3" % "3.18.0", + {{/useReflectionEqualsHashCode}} + {{#joda}} + "joda-time" % "joda-time" % "2.12.0", + {{#isJackson}} + "{{jacksonPackage}}.datatype" % "jackson-datatype-joda" % "{{#useJackson3}}3.2.1{{/useJackson3}}{{^useJackson3}}2.22.1{{/useJackson3}}", + {{/isJackson}} + {{/joda}} + "jakarta.annotation" % "jakarta.annotation-api" % "{{#useJakartaEe}}2.1.1{{/useJakartaEe}}{{^useJakartaEe}}1.3.5{{/useJakartaEe}}", + {{#withAWSV4Signature}} + "software.amazon.awssdk" % "auth" % "2.20.157", + {{/withAWSV4Signature}} + {{#dynamicOperations}} + "io.swagger.parser.v3" % "swagger-parser-v3" % "2.0.30", + {{/dynamicOperations}} + {{#parcelableModel}} + "com.google.android" % "android" % "4.1.1.4" % "provided", + {{/parcelableModel}} + {{#useBeanValidation}} + "jakarta.validation" % "jakarta.validation-api" % "{{#useJakartaEe}}3.0.2{{/useJakartaEe}}{{^useJakartaEe}}2.0.2{{/useJakartaEe}}", + {{/useBeanValidation}} + {{#performBeanValidation}} + {{#useJakartaEe}} + "org.hibernate.validator" % "hibernate-validator" % "8.0.3.Final", + "jakarta.el" % "jakarta.el-api" % "5.0.1", + "org.glassfish.expressly" % "expressly" % "5.0.0", + {{/useJakartaEe}} + {{^useJakartaEe}} + "org.hibernate.validator" % "hibernate-validator" % "6.2.5.Final", + "org.glassfish" % "jakarta.el" % "3.0.4", + {{/useJakartaEe}} + {{/performBeanValidation}} + "org.junit.jupiter" % "junit-jupiter-api" % "5.10.3" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/javaBuilder.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/javaBuilder.mustache new file mode 100644 index 000000000000..f8aef01a175d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/javaBuilder.mustache @@ -0,0 +1,101 @@ +public static class Builder {{#parentModel}}extends {{classname}}.Builder {{/parentModel}}{ + + private {{classname}} instance; + + public Builder() { + this(new {{classname}}()); + } + + protected Builder({{classname}} instance) { + {{#parentModel}} + super(instance); + {{/parentModel}} + this.instance = instance; + } + + {{#vars}} + public {{classname}}.Builder {{name}}({{>nullableArgument_builder}} {{name}}) { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + this.instance.{{name}} = JsonNullable.<{{#removeAnnotations}}{{{datatypeWithEnum}}}{{/removeAnnotations}}>of({{name}}); + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + this.instance.{{name}} = {{name}}; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + return this; + } + {{#vendorExtensions.x-is-jackson-optional-nullable}} + public {{classname}}.Builder {{name}}(JsonNullable<{{#removeAnnotations}}{{{datatypeWithEnum}}}{{/removeAnnotations}}> {{name}}) { + this.instance.{{name}} = {{name}}; + return this; + } + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{/vars}} + +{{#parentVars}} + public {{classname}}.Builder {{name}}({{>nullableArgument_builder}} {{name}}) { // inherited: {{isInherited}} + super.{{name}}({{name}}); + return this; + } + {{#vendorExtensions.x-is-jackson-optional-nullable}} + public {{classname}}.Builder {{name}}(JsonNullable<{{#removeAnnotations}}{{{datatypeWithEnum}}}{{/removeAnnotations}}> {{name}}) { + this.instance.{{name}} = {{name}}; + return this; + } + {{/vendorExtensions.x-is-jackson-optional-nullable}} + + {{/parentVars}} + +{{#isAdditionalPropertiesTrue}} + /** + * Copies the additional (undeclared) properties into the instance under construction. + * (Named putAdditionalProperties rather than additionalProperties so that it cannot collide with the + * builder setter generated for a declared property that happens to be called additionalProperties.) + * + * The values are put through {@link {{classname}}#putAdditionalProperty}, so the map is + * rebuilt on the instance that actually owns it: a subclass declares its own holder that + * shadows the parent one, and the virtual call always reaches the subclass field. + */ + public {{classname}}.Builder putAdditionalProperties(Map additionalProperties) { + if (additionalProperties != null) { + additionalProperties.forEach(this.instance::putAdditionalProperty); + } + return this; + } + +{{/isAdditionalPropertiesTrue}} + /** + * returns a built {{classname}} instance. + * + * The builder is not reusable. + */ + public {{classname}} build() { + try { + return this.instance; + } finally { + // ensure that this.instance is not reused{{#parentModel}} + super.build();{{/parentModel}} + this.instance = null; + } + } + + @Override + public String toString() { + return getClass() + "=(" + instance + ")"; + } + } + + /** + * Create a builder with no initialized field. + */ + public static {{classname}}.Builder builder() { + return new {{classname}}.Builder(); + } + + /** + * Create a builder with a shallow copy of this instance. + */ + public {{classname}}.Builder toBuilder() { + return new {{classname}}.Builder(){{#allVars}} + .{{name}}({{getter}}()){{/allVars}}{{#isAdditionalPropertiesTrue}} + .putAdditionalProperties(getAdditionalProperties()){{/isAdditionalPropertiesTrue}}; + } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/model.mustache new file mode 100644 index 000000000000..213e83ab2bad --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/model.mustache @@ -0,0 +1,35 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#useReflectionEqualsHashCode}} +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +{{/useReflectionEqualsHashCode}} +import java.util.Objects; +{{#imports}} +import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#withXml}} +import {{javaxPackage}}.xml.bind.annotation.*; +{{/withXml}} +{{#parcelableModel}} +import android.os.Parcelable; +import android.os.Parcel; +{{/parcelableModel}} +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} +{{#performBeanValidation}} +import org.hibernate.validator.constraints.*; +{{/performBeanValidation}} + +{{#models}} +{{#model}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#vendorExtensions.x-is-one-of-interface}}{{>oneof_interface}}{{/vendorExtensions.x-is-one-of-interface}}{{^vendorExtensions.x-is-one-of-interface}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/vendorExtensions.x-is-one-of-interface}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/modelEnum.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/modelEnum.mustache new file mode 100644 index 000000000000..aa59166be3c5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/modelEnum.mustache @@ -0,0 +1,127 @@ +{{#isGson}} +import java.io.IOException; +{{/isGson}} +{{#isUri}} +import java.net.URI; +{{/isUri}} +{{#isGson}} +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; +{{/isGson}} +{{#isJackson}} +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +{{/isJackson}} +{{#isJsonb}} +import jakarta.json.bind.adapter.JsonbAdapter; +import jakarta.json.bind.annotation.JsonbTypeAdapter; +{{/isJsonb}} + +/** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +{{#isDeprecated}} +@Deprecated +{{/isDeprecated}} +{{#isGson}} +@JsonAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.Adapter.class) +{{/isGson}} +{{#isJsonb}}{{! JSON-B has no @JsonValue equivalent; without an adapter the constant name would be + written instead of the wire value. }} +@JsonbTypeAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.Adapter.class) +{{/isJsonb}} +{{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}{{#vendorExtensions.x-implements}}{{#-first}} implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + {{#allowableValues}}{{#enumVars}} + {{#enumDescription}} + /** + * {{.}} + */ + {{/enumDescription}} + {{#withXml}} + @XmlEnumValue({{#lambda.javaStringLiteral}}{{{rawValue}}}{{/lambda.javaStringLiteral}}) + {{/withXml}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + {{#isJackson}} + @JsonValue + {{/isJackson}} + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + {{#isJackson}} + @JsonCreator + {{/isJackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.equals{{#isString}}{{#useEnumCaseInsensitive}}IgnoreCase{{/useEnumCaseInsensitive}}{{/isString}}(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}{{#enumUnknownDefaultCase}}{{#allowableValues}}{{#enumVars}}{{#-last}}return {{{name}}};{{/-last}}{{/enumVars}}{{/allowableValues}}{{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/enumUnknownDefaultCase}}{{/isNullable}} + } + + {{#isGson}} + public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}> { + @Override + public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} enumeration) throws IOException { + jsonWriter.value(enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}); + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}}{{#isUri}}URI.create({{/isUri}}jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{#isUri}}nextString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; + return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new java.math.BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isUri}}URI.create({{/isUri}}jsonElement.{{#isNumber}}getAsString(){{/isNumber}}{{#isInteger}}getAsInt(){{/isInteger}}{{#isUri}}getAsString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}getAs{{{dataType}}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new java.math.BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + {{/isGson}} + {{#isJsonb}} + public static class Adapter implements JsonbAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}, {{#isUri}}String{{/isUri}}{{^isUri}}{{{dataType}}}{{/isUri}}> { + @Override + public {{#isUri}}String{{/isUri}}{{^isUri}}{{{dataType}}}{{/isUri}} adaptToJson({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} enumeration) { + return enumeration == null ? null : enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}; + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} adaptFromJson({{#isUri}}String{{/isUri}}{{^isUri}}{{{dataType}}}{{/isUri}} value) { + return value == null ? null : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue({{#isUri}}URI.create(value){{/isUri}}{{^isUri}}value{{/isUri}}); + } + } + {{/isJsonb}} +{{#supportUrlQuery}} + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format(java.util.Locale.ROOT, "%s=%s", prefix, this.toString()); + } +{{/supportUrlQuery}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/modelInnerEnum.mustache new file mode 100644 index 000000000000..f9937da48b45 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/modelInnerEnum.mustache @@ -0,0 +1,93 @@ + /** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ + {{#isGson}} + @JsonAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.Adapter.class) + {{/isGson}} + {{#isJsonb}}{{! JSON-B has no @JsonValue equivalent; without an adapter the constant name would be + written instead of the wire value. }} + @JsonbTypeAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.Adapter.class) + {{/isJsonb}} +{{#withXml}} + @XmlType(name="{{datatypeWithEnum}}") + @XmlEnum({{dataType}}.class) +{{/withXml}} + {{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-implements}}{{#-first}} implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}} { + {{#allowableValues}} + {{#enumVars}} + {{#enumDescription}} + /** + * {{.}} + */ + {{/enumDescription}} + {{#withXml}} + @XmlEnumValue({{#lambda.javaStringLiteral}}{{{rawValue}}}{{/lambda.javaStringLiteral}}) + {{/withXml}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + {{#isJackson}} + @JsonValue + {{/isJackson}} + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + {{#isJackson}} + @JsonCreator + {{/isJackson}} + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if ({{#isString}}{{#useEnumCaseInsensitive}}b.value{{#dataFormat}}.toString(){{/dataFormat}}.equalsIgnoreCase({{#dataFormat}}value == null ? null : value.toString(){{/dataFormat}}{{^dataFormat}}value{{/dataFormat}}){{/useEnumCaseInsensitive}}{{^useEnumCaseInsensitive}}b.value.equals(value){{/useEnumCaseInsensitive}}{{/isString}}{{^isString}}b.value.equals(value){{/isString}}) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}{{#enumUnknownDefaultCase}}{{#allowableValues}}{{#enumVars}}{{#-last}}return {{{name}}};{{/-last}}{{/enumVars}}{{/allowableValues}}{{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/enumUnknownDefaultCase}}{{/isNullable}} + } + + {{#isGson}} + public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}> { + @Override + public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} enumeration) throws IOException { + jsonWriter.value(enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}{{#isUuid}}.toString(){{/isUuid}}); + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}} {{#isUuid}}UUID.fromString({{/isUuid}}{{#isUri}}URI.create({{/isUri}}jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{#isUri}}nextString()){{/isUri}}{{#isUuid}}nextString()){{/isUuid}}{{^isNumber}}{{^isInteger}}{{^isUri}}{{^isUuid}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isUuid}}{{/isUri}}{{/isInteger}}{{/isNumber}}; + return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new java.math.BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isUuid}}UUID.fromString({{/isUuid}}{{#isUri}}URI.create({{/isUri}}jsonElement.{{#isNumber}}getAsString(){{/isNumber}}{{#isInteger}}getAsInt(){{/isInteger}}{{#isUri}}getAsString()){{/isUri}}{{#isUuid}}getAsString()){{/isUuid}}{{^isNumber}}{{^isInteger}}{{^isUri}}{{^isUuid}}getAs{{{dataType}}}(){{/isUuid}}{{/isUri}}{{/isInteger}}{{/isNumber}}; + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new java.math.BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + {{/isGson}} + {{#isJsonb}} + public static class Adapter implements JsonbAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}, {{#isUri}}String{{/isUri}}{{^isUri}}{{{dataType}}}{{/isUri}}> { + @Override + public {{#isUri}}String{{/isUri}}{{^isUri}}{{{dataType}}}{{/isUri}} adaptToJson({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} enumeration) { + return enumeration == null ? null : enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}; + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} adaptFromJson({{#isUri}}String{{/isUri}}{{^isUri}}{{{dataType}}}{{/isUri}} value) { + return value == null ? null : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isUri}}URI.create(value){{/isUri}}{{^isUri}}value{{/isUri}}); + } + } + {{/isJsonb}} + } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/model_test.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/model_test.mustache new file mode 100644 index 000000000000..eb1643edf8cc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/model_test.mustache @@ -0,0 +1,43 @@ +{{>licenseInfo}} + +package {{package}}; + +{{! The model's import list is serialization-library specific and nothing below uses it: the test bodies + are stubs and the model itself is in this package. Echoing it here pulled Jackson annotations into + Gson and JSON-B builds, which do not have them on the classpath. }} +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for {{classname}} + */ +public class {{classname}}Test { + {{#models}} + {{#model}} + {{^vendorExtensions.x-is-one-of-interface}} + {{^isEnum}} + private final {{classname}} model = new {{classname}}(); + + {{/isEnum}} + /** + * Model tests for {{classname}} + */ + @Test + public void test{{classname}}() { + // TODO: test {{classname}} + } + + {{#allVars}} + /** + * Test the property '{{name}}' + */ + @Test + public void {{name}}Test() { + // TODO: test {{name}} + } + + {{/allVars}} + {{/vendorExtensions.x-is-one-of-interface}} + {{/model}} + {{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/oneof_model.mustache new file mode 100644 index 000000000000..edee83b9d544 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/oneof_model.mustache @@ -0,0 +1,1326 @@ +{{#isGson}} +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +{{! TypeAdapter, JsonAdapter, SerializedName, JsonReader and JsonWriter are contributed via + model.imports by JavaClientCodegen; emitting them here as well produced duplicates. }} +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +{{/isGson}} +{{#isJackson}} +{{#isAdditionalPropertiesTrue}} +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +{{/isAdditionalPropertiesTrue}} +import {{jacksonPackage}}.core.JsonGenerator; +import {{jacksonPackage}}.core.JsonParser; +import {{jacksonPackage}}.core.JsonToken; +import {{jacksonPackage}}.core.type.TypeReference; +import {{jacksonPackage}}.databind.DeserializationContext; +{{^useJackson3}} +import {{jacksonPackage}}.databind.JsonMappingException; +{{/useJackson3}} +import {{jacksonPackage}}.databind.JsonNode; +{{^useJackson3}} +import {{jacksonPackage}}.databind.MapperFeature; +{{/useJackson3}} +{{^useJackson3}} +import {{jacksonPackage}}.databind.SerializerProvider; +{{/useJackson3}} +import {{jacksonPackage}}.databind.annotation.JsonDeserialize; +import {{jacksonPackage}}.databind.annotation.JsonSerialize; +import {{jacksonPackage}}.databind.deser.std.StdDeserializer; +import {{jacksonPackage}}.databind.ser.std.StdSerializer; +{{#useJackson3}} +import {{jacksonPackage}}.core.JacksonException; +import {{jacksonPackage}}.databind.DatabindException; +import {{jacksonPackage}}.databind.SerializationContext; +{{/useJackson3}} +{{/isJackson}} + +{{#isJsonb}} +{{! additional_properties.mustache annotates its holder field with @JsonbTransient, so the + import has to be here too - a pojo gets it from pojo.mustache, a composed model does not. }} +import jakarta.json.bind.annotation.JsonbTransient; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; +{{/isJsonb}} +{{! java.io.IOException, java.util.ArrayList, java.util.HashMap, java.util.List and + java.util.Map are contributed via model.imports by JavaClientCodegen.fromModel, which is + also where codegen imports them for container properties. Emitting them here as well + produced duplicate import lines. The rest have no Java importMapping entry and are not + duplicated, so they stay. }} +{{^isJackson}} +import java.lang.reflect.Type; +{{/isJackson}} +{{^isJsonb}} +import java.util.logging.Level; +{{/isJsonb}} +import java.util.logging.Logger; +{{#isJackson}} +import java.util.Collections; +{{/isJackson}} +import java.util.HashSet; +{{! java.util.Objects is already imported by model.mustache for every model it renders. }} +{{#supportUrlQuery}} +import java.util.StringJoiner; +{{/supportUrlQuery}} + +import {{invokerPackage}}.JSON; + +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} +{{#isJackson}} +@JsonDeserialize(using = {{classname}}.{{classname}}Deserializer.class) +@JsonSerialize(using = {{classname}}.{{classname}}Serializer.class) +{{/isJackson}} +{{#isJsonb}} +@JsonbTypeDeserializer({{classname}}.{{classname}}Deserializer.class) +@JsonbTypeSerializer({{classname}}.{{classname}}Serializer.class) +{{/isJsonb}} +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { + private static final Logger log = Logger.getLogger({{classname}}.class.getName()); + +{{>additional_properties}} + {{#isAdditionalPropertiesTrue}} + {{#isGson}} + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties({{classname}} instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties({{classname}} value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + {{/isGson}} + {{#isJackson}} + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties({{classname}} instance, JsonNode tree) { + if (tree == null || !tree.isObject() || instance.getActualInstance() == null) { + return; + } + JsonNode consumed = JSON.getMapper().valueToTree(instance.getActualInstance()); + if (consumed == null || !consumed.isObject()) { + return; + } + java.util.Iterator> fields = tree.{{^useJackson3}}fields{{/useJackson3}}{{#useJackson3}}properties{{/useJackson3}}(){{#useJackson3}}.iterator(){{/useJackson3}}; + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + if (consumed.has(entry.getKey())) { + continue; + } + instance.putAdditionalProperty(entry.getKey(), + JSON.getMapper().convertValue(entry.getValue(), Object.class)); + } + } + {{/isJackson}} + {{/isAdditionalPropertiesTrue}} + + {{#isGson}} + /** + * 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 {{classname}} + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("{{{propertyBaseName}}}") == null) { + throw new IOException("Failed to deserialize as the discriminator field '{{{propertyBaseName}}}' is missing."); + } + String discriminatorValue = jsonObject.get("{{{propertyBaseName}}}").getAsString(); + {{#mappedModels}} + if ("{{{mappingName}}}".equals(discriminatorValue)) { + {{{modelName}}}.validateJsonElement(jsonElement); + return; + } + {{/mappedModels}} + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // deserialize {{{dataType}}} + try { + // validate the JSON object to see if any exception is thrown + {{#isModel}} + {{#hasChildren}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/hasChildren}} + {{^hasChildren}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isMap}} + {{^isMap}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isMap}} + {{/isArray}} + {{/hasChildren}} + {{/isModel}} + {{^isModel}} + {{#isNumber}} + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isNumber}} + {{^isNumber}} + {{#isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#isNumber}} + if (!element.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type Number in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#isNumber}} + if (!entry.getValue().getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type Number in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!entry.getValue().getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isMap}} + {{^isMap}} + {{^isAnyType}} + if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isAnyType}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(element); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(element.getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!element.isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected array items to be a primitive type in the JSON string but got `%s`", element.toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(entry.getValue()); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(entry.getValue().getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!entry.getValue().isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected map values to be a primitive type in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isMap}} + {{^isMap}} + {{#isUuid}} + UUID.fromString(jsonElement.getAsString()); + {{/isUuid}} + {{^isUuid}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isUuid}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{/isNumber}} + {{/isModel}} + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage())); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/oneOf}} + {{/composedSchemas}} + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for {{classname}}: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!{{classname}}.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes '{{classname}}' and its subtypes + } + {{#vendorExtensions.x-gson-large-oneof}} + return (TypeAdapter) new TypeAdapter<{{classname}}>() { + {{/vendorExtensions.x-gson-large-oneof}} + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + {{#composedSchemas}} + {{#oneOf}} + {{^isArray}} + {{^isMap}} + {{^vendorExtensions.x-duplicated-data-type}} + final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = gson.getDelegateAdapter({{#vendorExtensions.x-gson-large-oneof}}CustomTypeAdapterFactory.this{{/vendorExtensions.x-gson-large-oneof}}{{^vendorExtensions.x-gson-large-oneof}}this{{/vendorExtensions.x-gson-large-oneof}}, TypeToken.get({{{dataType}}}.class)); + {{/vendorExtensions.x-duplicated-data-type}} + {{/isMap}} + {{/isArray}} + {{#isArray}} + final Type typeInstance{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = new TypeToken<{{{dataType}}}>(){}.getType(); + final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = (TypeAdapter<{{{dataType}}}>) gson.getDelegateAdapter({{#vendorExtensions.x-gson-large-oneof}}CustomTypeAdapterFactory.this{{/vendorExtensions.x-gson-large-oneof}}{{^vendorExtensions.x-gson-large-oneof}}this{{/vendorExtensions.x-gson-large-oneof}}, TypeToken.get(typeInstance{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}})); + {{/isArray}} + {{#isMap}} + final Type typeInstance{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = new TypeToken<{{{dataType}}}>(){}.getType(); + final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}} = (TypeAdapter<{{{dataType}}}>) gson.getDelegateAdapter({{#vendorExtensions.x-gson-large-oneof}}CustomTypeAdapterFactory.this{{/vendorExtensions.x-gson-large-oneof}}{{^vendorExtensions.x-gson-large-oneof}}this{{/vendorExtensions.x-gson-large-oneof}}, TypeToken.get(typeInstance{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}})); + {{/isMap}} + {{/oneOf}} + {{/composedSchemas}} + + {{^vendorExtensions.x-gson-large-oneof}} + return (TypeAdapter) new TypeAdapter<{{classname}}>() { + {{/vendorExtensions.x-gson-large-oneof}} + @Override + public void write(JsonWriter out, {{classname}} value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // check if the actual instance is of the type `{{{dataType}}}` + if (value.getActualInstance() instanceof {{#isArray}}List{{/isArray}}{{#isMap}}Map{{/isMap}}{{^isMap}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isMap}}) { + element = adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}}.toJsonTree(({{{dataType}}})value.getActualInstance()); + } + {{/vendorExtensions.x-duplicated-data-type}} + {{/oneOf}} + {{/composedSchemas}} + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}"); + } + + {{#isAdditionalPropertiesTrue}} + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + {{/isAdditionalPropertiesTrue}} + elementAdapter.write(out, element); + } + + @Override + public {{classname}} read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("{{{propertyBaseName}}}") == null) { + throw new IOException("Failed to deserialize as the discriminator field '{{{propertyBaseName}}}' is missing."); + } + String discriminatorValue = jsonObject.get("{{{propertyBaseName}}}").getAsString(); + {{#mappedModels}} + if ("{{{mappingName}}}".equals(discriminatorValue)) { + deserialized = adapter{{#sanitizeDataType}}{{{modelName}}}{{/sanitizeDataType}}.fromJsonTree(jsonElement); + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(ret, jsonElement, gson); + {{/isAdditionalPropertiesTrue}} + return ret; + } + {{/mappedModels}} + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + {{#composedSchemas}} + {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // deserialize {{{dataType}}} + try { + // validate the JSON object to see if any exception is thrown + {{#isModel}} + {{#hasChildren}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/hasChildren}} + {{^hasChildren}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isMap}} + {{^isMap}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isMap}} + {{/isArray}} + {{/hasChildren}} + {{/isModel}} + {{^isModel}} + {{#isNumber}} + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isNumber}} + {{^isNumber}} + {{#isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#isNumber}} + if (!element.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type Number in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", element.toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + {{#items}} + {{^isAnyType}} + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#isNumber}} + if (!entry.getValue().getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type Number in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + {{^isNumber}} + if (!entry.getValue().getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected map values to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/isNumber}} + } + {{/isAnyType}} + {{/items}} + {{/isMap}} + {{^isMap}} + {{^isAnyType}} + if (!jsonElement.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isAnyType}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isArray}} + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(element); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(element.getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!element.isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected array items to be a primitive type in the JSON string but got `%s`", element.toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isArray}} + {{^isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + {{#items.isModel}} + {{{items.dataType}}}.validateJsonElement(entry.getValue()); + {{/items.isModel}} + {{^items.isModel}} + {{#items.isUuid}} + UUID.fromString(entry.getValue().getAsString()); + {{/items.isUuid}} + {{^items.isUuid}} + if (!entry.getValue().isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected map values to be a primitive type in the JSON string but got `%s`", entry.getValue().toString())); + } + {{/items.isUuid}} + {{/items.isModel}} + } + {{/isMap}} + {{^isMap}} + {{#isUuid}} + UUID.fromString(jsonElement.getAsString()); + {{/isUuid}} + {{^isUuid}} + {{{dataType}}}.validateJsonElement(jsonElement); + {{/isUuid}} + {{/isMap}} + {{/isArray}} + {{/isPrimitiveType}} + {{/isNumber}} + {{/isModel}} + actualAdapter = adapter{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}}; + match++; + log.log(Level.FINER, "Input data matches schema '{{{dataType}}}'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/oneOf}} + {{/composedSchemas}} + if (match == 1) { + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(ret, jsonElement, gson); + {{/isAdditionalPropertiesTrue}} + return ret; + } + + throw new IOException(String.format("Failed deserialization for {{classname}}: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + {{/isGson}} + + {{#isJackson}} + public static class {{classname}}Serializer extends StdSerializer<{{classname}}> { + public {{classname}}Serializer(Class<{{classname}}> t) { + super(t); + } + + public {{classname}}Serializer() { + this(null); + } + + @Override + public void serialize({{classname}} value, JsonGenerator jgen, {{^useJackson3}}SerializerProvider provider{{/useJackson3}}{{#useJackson3}}SerializationContext serializationContext{{/useJackson3}}) throws {{^useJackson3}}IOException{{/useJackson3}}{{#useJackson3}}JacksonException{{/useJackson3}} { + {{#isAdditionalPropertiesTrue}} + {{! @JsonAnyGetter is ignored on a class with a custom serializer, so the unconsumed + properties have to be merged into the child's tree by hand. }} + if (value.getActualInstance() != null && value.getAdditionalProperties() != null + && !value.getAdditionalProperties().isEmpty()) { + JsonNode node = JSON.getMapper().valueToTree(value.getActualInstance()); + if (node != null && node.isObject()) { + {{jacksonPackage}}.databind.node.ObjectNode objectNode = ({{jacksonPackage}}.databind.node.ObjectNode) node; + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (objectNode.has(entry.getKey())) { + // the child schema owns this property + continue; + } + objectNode.set(entry.getKey(), JSON.getMapper().valueToTree(entry.getValue())); + } + {{^useJackson3}} + jgen.writeTree(node); + {{/useJackson3}} + {{#useJackson3}} + serializationContext.writeValue(jgen, node); + {{/useJackson3}} + return; + } + } + {{/isAdditionalPropertiesTrue}} + {{^useJackson3}} + jgen.writeObject(value.getActualInstance()); + {{/useJackson3}} + {{#useJackson3}} + serializationContext.writeValue(jgen, value.getActualInstance()); + {{/useJackson3}} + } + } + + public static class {{classname}}Deserializer extends StdDeserializer<{{classname}}> { + public {{classname}}Deserializer() { + this({{classname}}.class); + } + + public {{classname}}Deserializer(Class vc) { + super(vc); + } + + @Override + public {{classname}} deserialize(JsonParser jp, DeserializationContext ctxt) throws {{^useJackson3}}IOException{{/useJackson3}}{{#useJackson3}}JacksonException{{/useJackson3}} { + JsonNode tree = ctxt.readTree(jp); + Object deserialized = null; + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + {{classname}} new{{classname}} = new {{classname}}(); + {{^useJackson3}} + Map result2 = tree.traverse(jp.getCodec()).readValueAs(new TypeReference>() {}); + String discriminatorValue = (String)result2.get("{{{propertyBaseName}}}"); + {{/useJackson3}} + {{#useJackson3}} + String discriminatorValue = tree.path("{{{propertyBaseName}}}").asText(null); + {{/useJackson3}} + if (discriminatorValue != null) { + switch (discriminatorValue) { + {{#mappedModels}} + case "{{{mappingName}}}": + {{^useJackson3}} + deserialized = tree.traverse(jp.getCodec()).readValueAs({{{modelName}}}.class); + {{/useJackson3}} + {{#useJackson3}} + deserialized = ctxt.readTreeAsValue(tree, {{{modelName}}}.class); + {{/useJackson3}} + new{{classname}}.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(new{{classname}}, tree); + {{/isAdditionalPropertiesTrue}} + return new{{classname}}; + {{/mappedModels}} + default: + log.log(Level.WARNING, String.format(java.util.Locale.ROOT, "Failed to lookup discriminator value `%s` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); + } + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + {{^useJackson3}} + boolean typeCoercion = ctxt.isEnabled(MapperFeature.ALLOW_COERCION_OF_SCALARS); + {{/useJackson3}} + {{#useJackson3}} + boolean typeCoercion = false; + {{/useJackson3}} + int match = 0; + {{^useJackson3}} + JsonToken token = tree.traverse(jp.getCodec()).nextToken(); + {{/useJackson3}} + {{#useJackson3}} + JsonToken token = tree.asToken(); + {{/useJackson3}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // deserialize {{{dataType}}} + try { + boolean attemptParsing = true; + // ensure that we respect type coercion as set on the client ObjectMapper + if ({{{baseType}}}.class.equals(Integer.class) || {{{baseType}}}.class.equals(Long.class) || {{{baseType}}}.class.equals(Float.class) || {{{baseType}}}.class.equals(Double.class) || {{{baseType}}}.class.equals(Boolean.class) || {{{baseType}}}.class.equals(String.class)) { + attemptParsing = typeCoercion; + if (!attemptParsing) { + attemptParsing |= (({{{baseType}}}.class.equals(Integer.class) || {{{baseType}}}.class.equals(Long.class)) && token == JsonToken.VALUE_NUMBER_INT); + attemptParsing |= (({{{baseType}}}.class.equals(Float.class) || {{{baseType}}}.class.equals(Double.class)) && token == JsonToken.VALUE_NUMBER_FLOAT); + attemptParsing |= ({{{baseType}}}.class.equals(Boolean.class) && (token == JsonToken.VALUE_FALSE || token == JsonToken.VALUE_TRUE)); + attemptParsing |= ({{{baseType}}}.class.equals(String.class) && token == JsonToken.VALUE_STRING); + {{#isNullable}} + attemptParsing |= (token == JsonToken.VALUE_NULL); + {{/isNullable}} + } + } + if (attemptParsing) { + {{^useJackson3}} + deserialized = tree.traverse(jp.getCodec()).readValueAs(new TypeReference<{{{dataType}}}>() {}); + {{/useJackson3}} + {{#useJackson3}} + deserialized = ctxt.readTreeAsValue(tree, ctxt.getTypeFactory().constructType(new TypeReference<{{{dataType}}}>() {})); + {{/useJackson3}} + // TODO: there is no validation against JSON schema constraints + // (min, max, enum, pattern...), this does not perform a strict JSON + // validation, which means the 'match' count may be higher than it should be. + match++; + log.log(Level.FINER, "Input data matches schema '{{{dataType}}}'"); + } + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema '{{{dataType}}}'", e); + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + if (match == 1) { + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + collectUnconsumedProperties(ret, tree); + {{/isAdditionalPropertiesTrue}} + return ret; + } + {{^useJackson3}} + throw new IOException(String.format(java.util.Locale.ROOT, "Failed deserialization for {{classname}}: %d classes match result, expected 1", match)); + {{/useJackson3}} + {{#useJackson3}} + throw DatabindException.from(jp, String.format(java.util.Locale.ROOT, "Failed deserialization for {{classname}}: %d classes match result, expected 1", match)); + {{/useJackson3}} + } + + /** + * Handle deserialization of the 'null' value. + */ + @Override + {{^useJackson3}} + public {{classname}} getNullValue(DeserializationContext ctxt) throws JsonMappingException { + {{/useJackson3}} + {{#useJackson3}} + public {{classname}} getNullValue(DeserializationContext ctxt) { + {{/useJackson3}} + {{#isNullable}} + return null; + {{/isNullable}} + {{^isNullable}} + {{^useJackson3}} + throw new JsonMappingException(ctxt.getParser(), "{{classname}} cannot be null"); + {{/useJackson3}} + {{#useJackson3}} + throw DatabindException.from(ctxt.getParser(), "{{classname}} cannot be null"); + {{/useJackson3}} + {{/isNullable}} + } + } + {{/isJackson}} + + {{#isJsonb}} + public static class {{classname}}Serializer implements JsonbSerializer<{{classname}}> { + @Override + public void serialize({{classname}} obj, JsonGenerator generator, SerializationContext ctx) { + if (obj.getActualInstance() == null) { + generator.writeNull(); + return; + } + {{#isAdditionalPropertiesTrue}} + if (obj.getAdditionalProperties() != null && !obj.getAdditionalProperties().isEmpty()) { + JsonObject childObject = toJsonObject(obj.getActualInstance()); + if (childObject != null) { + jakarta.json.JsonObjectBuilder builder = jakarta.json.Json.createObjectBuilder(childObject); + for (Map.Entry entry : obj.getAdditionalProperties().entrySet()) { + if (childObject.containsKey(entry.getKey())) { + // the child schema owns this property + continue; + } + builder.add(entry.getKey(), toJsonValue(entry.getValue())); + } + ctx.serialize(builder.build(), generator); + return; + } + } + {{/isAdditionalPropertiesTrue}} + ctx.serialize(obj.getActualInstance(), generator); + } + } + {{#isAdditionalPropertiesTrue}} + + /** + * Render a value through JSON-B and read it back as a JsonObject, or null if it is not an object. + */ + private static JsonObject toJsonObject(Object value) { + try (jakarta.json.JsonReader reader = jakarta.json.Json.createReader( + new java.io.StringReader(JSON.getJsonb().toJson(value)))) { + jakarta.json.JsonStructure structure = reader.read(); + return structure instanceof JsonObject ? (JsonObject) structure : null; + } catch (Exception e) { + return null; + } + } + + private static jakarta.json.JsonValue toJsonValue(Object value) { + if (value == null) { + return jakarta.json.JsonValue.NULL; + } + try (jakarta.json.JsonReader reader = jakarta.json.Json.createReader( + new java.io.StringReader(JSON.getJsonb().toJson(value)))) { + return reader.readValue(); + } + } + + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties({{classname}} instance, JsonObject jsonObject) { + if (jsonObject == null || instance.getActualInstance() == null) { + return; + } + JsonObject consumed = toJsonObject(instance.getActualInstance()); + if (consumed == null) { + return; + } + for (Map.Entry entry : jsonObject.entrySet()) { + if (consumed.containsKey(entry.getKey())) { + continue; + } + instance.putAdditionalProperty(entry.getKey(), fromJsonValue(entry.getValue())); + } + } + + private static Object fromJsonValue(jakarta.json.JsonValue value) { + switch (value.getValueType()) { + case STRING: + return ((jakarta.json.JsonString) value).getString(); + case NUMBER: + return ((jakarta.json.JsonNumber) value).numberValue(); + case TRUE: + return Boolean.TRUE; + case FALSE: + return Boolean.FALSE; + case NULL: + return null; + default: + return JSON.getJsonb().fromJson(value.toString(), + value.getValueType() == jakarta.json.JsonValue.ValueType.ARRAY + ? List.class : HashMap.class); + } + } + {{/isAdditionalPropertiesTrue}} + + {{! The DeserializationContext handed to a JsonbDeserializer belongs to the parse that is + already running: Yasson wraps whatever parser reaches ctx.deserialize in a YassonParser + whose scope bookkeeping is taken from the context, not from that parser. Handing it a + second, freshly created parser therefore produces a wrapper that believes it already + sits at the end of the outer value, so the branch's own deserializer fails in + getObject()/getValue() with NoSuchElementException or an NPE - and once one attempt has + left those counters askew a later branch binds whatever it is handed. Bind the branch + through the binding API instead, which runs a parse of its own. }} + private static Object deserializeBranch(Class type, JsonValue value) { + if (!branchAcceptsValueType(type, value)) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, + "Expected the JSON value to bind as %s but got `%s`", type.getSimpleName(), value)); + } + {{! getJsonb(), not getPlainJsonb(): a branch can itself be a discriminated-hierarchy + root, and the concrete-subtype dispatch for those lives in a deserializer that only + the main instance carries. Binding a branch never re-enters this wrapper, so there + is no recursion to break by dropping to the plain instance. }} + return JSON.getJsonb().fromJson(value.toString(), type); + } + + {{! Yasson binds by coercion, so a branch whose Java type has nothing to do with the JSON + value at hand still "matches": String swallows a number or a boolean and a numeric type + swallows a numeric string, which leaves a composed schema of scalars permanently + ambiguous. Gate on the JSON value type first - the Gson branch of this template does + the same thing through its generated per-branch validateJsonElement checks. }} + private static boolean branchAcceptsValueType(Class type, JsonValue value) { + if (type == Object.class) { + // an 'any type' branch takes whatever it is handed + return true; + } + if (AbstractOpenApiSchema.class.isAssignableFrom(type)) { + // a branch that is itself a composed schema decides for itself which JSON shapes + // it accepts - a oneOf of scalars nested inside another oneOf binds a scalar here + return true; + } + boolean sequence = java.util.Collection.class.isAssignableFrom(type) + || (type.isArray() && type != byte[].class); + switch (value.getValueType()) { + case ARRAY: + return sequence; + case OBJECT: + return !sequence && !bindsFromJsonScalar(type); + case TRUE: + case FALSE: + return type == Boolean.class || type == boolean.class; + case NUMBER: + return Number.class.isAssignableFrom(type) + || (type.isPrimitive() && type != boolean.class && type != char.class); + case STRING: + return !sequence + && !Number.class.isAssignableFrom(type) + && type != Boolean.class && type != boolean.class; + default: + return true; + } + } + + /** + * Whether a branch of this type binds from a JSON scalar rather than from a JSON object. + */ + private static boolean bindsFromJsonScalar(Class type) { + {{! byte[] is a scalar here on purpose: 'format: byte' arrives as a base64 string. }} + return type.isPrimitive() + || Number.class.isAssignableFrom(type) + || type == Boolean.class + || type == Character.class + || CharSequence.class.isAssignableFrom(type) + || type == java.util.UUID.class + || type == byte[].class + || type.isEnum(); + } + + public static class {{classname}}Deserializer implements JsonbDeserializer<{{classname}}> { + @Override + public {{classname}} deserialize(JsonParser parser, DeserializationContext ctx, Type rt) { + {{! A composed branch can be an array or a scalar, not only an object, and + parser.getObject() throws IllegalStateException on START_ARRAY. Read the + generic JsonValue and narrow only for the object-shaped paths below. }} + JsonValue jsonValue = parser.getValue(); + {{! Yasson routes a JSON null through this deserializer instead of short-circuiting + it, and every branch then fails to bind. Mirror the Jackson branch's + getNullValue: a nullable composed schema yields null, a non-nullable one is an + error. }} + if (jsonValue == null || jsonValue.getValueType() == JsonValue.ValueType.NULL) { + {{#isNullable}} + return null; + {{/isNullable}} + {{^isNullable}} + throw new RuntimeException("{{classname}} cannot be null"); + {{/isNullable}} + } + JsonObject jsonObject = jsonValue instanceof JsonObject ? (JsonObject) jsonValue : null; + Object deserialized = null; + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + if (jsonObject != null && jsonObject.containsKey("{{{propertyBaseName}}}")) { + String discriminatorValue = jsonObject.getString("{{{propertyBaseName}}}"); + {{#mappedModels}} + if ("{{{mappingName}}}".equals(discriminatorValue)) { + deserialized = deserializeBranch({{{modelName}}}.class, jsonValue); + {{classname}} new{{classname}} = new {{classname}}(); + new{{classname}}.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + if (jsonObject != null) { + collectUnconsumedProperties(new{{classname}}, jsonObject); + } + {{/isAdditionalPropertiesTrue}} + return new{{classname}}; + } + {{/mappedModels}} + } + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + int match = 0; + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + // deserialize {{{dataType}}} + try { + deserialized = deserializeBranch({{{baseType}}}.class, jsonValue); + match++; + } catch (Exception e) { + // deserialization failed, continue + } + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + if (match == 1) { + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + {{#isAdditionalPropertiesTrue}} + if (jsonObject != null) { + collectUnconsumedProperties(ret, jsonObject); + } + {{/isAdditionalPropertiesTrue}} + return ret; + } + throw new RuntimeException(String.format(java.util.Locale.ROOT, "Failed deserialization for {{classname}}: %d classes match result, expected 1", match)); + } + } + {{/isJsonb}} + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public {{classname}}() { + super("oneOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + } + + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + public {{classname}}({{{dataType}}} o) { + super("oneOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + setActualInstance(o); + } + {{/vendorExtensions.x-duplicated-data-type}} + + {{/composedSchemas.oneOf}} + static { + {{#composedSchemas.oneOf}} + schemas.put("{{{dataType}}}", {{{baseType}}}.class); + {{/composedSchemas.oneOf}} + {{#isJackson}} + JSON.registerDescendants({{classname}}.class, Collections.unmodifiableMap(schemas)); + {{#discriminator}} + // Initialize and register the discriminator mappings. + Map> mappings = new HashMap>(); + {{#mappedModels}} + mappings.put("{{mappingName}}", {{modelName}}.class); + {{/mappedModels}} + mappings.put("{{name}}", {{classname}}.class); + JSON.registerDiscriminator({{classname}}.class, "{{propertyBaseName}}", mappings); + {{/discriminator}} + {{/isJackson}} + } + + @Override + public Map> getSchemas() { + return {{classname}}.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}} + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + {{#isNullable}} + if (instance == null) { + super.setActualInstance(instance); + return; + } + + {{/isNullable}} + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if (JSON.isInstanceOf({{{baseType}}}.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + throw new RuntimeException("Invalid instance type. Must be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}"); + } + + /** + * Get the actual instance, which can be the following: + * {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}} + * + * @return The actual instance ({{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type-ignoring-erasure}} + /** + * Get the actual instance of `{{{dataType}}}`. If the actual instance is not `{{{dataType}}}`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `{{{dataType}}}` + * @throws ClassCastException if the instance is not `{{{dataType}}}` + */ + @SuppressWarnings("unchecked") + public {{{dataType}}} get{{#sanitizeDataType}}{{{dataType}}}{{/sanitizeDataType}}() throws ClassCastException { + return ({{{dataType}}})super.getActualInstance(); + } + + {{/vendorExtensions.x-duplicated-data-type-ignoring-erasure}} + {{/composedSchemas.oneOf}} + +{{#supportUrlQuery}} + + /** + * Convert the instance into URL query string. + * + * @return URL query string + */ + public String toUrlQueryString() { + return toUrlQueryString(null); + } + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + String suffix = ""; + String containerSuffix = ""; + String containerPrefix = ""; + if (prefix == null) { + // style=form, explode=true, e.g. /pet?name=cat&type=manx + prefix = ""; + } else { + // deepObject style e.g. /pet?id[name]=cat&id[type]=manx + prefix = prefix + "["; + suffix = "]"; + containerSuffix = "]"; + containerPrefix = "["; + } + + StringJoiner joiner = new StringJoiner("&"); + + {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} + if (getActualInstance() instanceof {{{dataType}}}) { + {{#isArray}} + {{#items.isPrimitiveType}} + {{#uniqueItems}} + if (getActualInstance() != null) { + int i = 0; + for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf(_item)))); + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if (getActualInstance() != null) { + for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf((({{{dataType}}})getActualInstance()).get(i))))); + } + } + {{/uniqueItems}} + {{/items.isPrimitiveType}} + {{^items.isPrimitiveType}} + {{#items.isModel}} + {{#uniqueItems}} + if (getActualInstance() != null) { + int i = 0; + for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) { + if (_item != null) { + joiner.add(_item.toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + i++; + } + {{/uniqueItems}} + {{^uniqueItems}} + if (getActualInstance() != null) { + for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) { + if ((({{{dataType}}})getActualInstance()).get(i) != null) { + joiner.add((({{{dataType}}})getActualInstance()).get(i).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix)))); + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{^items.isModel}} + {{#uniqueItems}} + if (getActualInstance() != null) { + int i = 0; + for ({{{items.dataType}}} _item : ({{{dataType}}})getActualInstance()) { + if (_item != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf(_item)))); + } + i++; + } + } + {{/uniqueItems}} + {{^uniqueItems}} + if (getActualInstance() != null) { + for (int i = 0; i < (({{{dataType}}})getActualInstance()).size(); i++) { + if (getActualInstance().get(i) != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, i, containerSuffix), + ApiClient.urlEncode(String.valueOf((({{{dataType}}})getActualInstance()).get(i))))); + } + } + } + {{/uniqueItems}} + {{/items.isModel}} + {{/items.isPrimitiveType}} + {{/isArray}} + {{^isArray}} + {{#isMap}} + {{#items.isPrimitiveType}} + if (getActualInstance() != null) { + for (String _key : (({{{dataType}}})getActualInstance()).keySet()) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s=%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix), + getActualInstance().get(_key), ApiClient.urlEncode(String.valueOf((({{{dataType}}})getActualInstance()).get(_key))))); + } + } + {{/items.isPrimitiveType}} + {{^items.isPrimitiveType}} + if (getActualInstance() != null) { + for (String _key : (({{{dataType}}})getActualInstance()).keySet()) { + if ((({{{dataType}}})getActualInstance()).get(_key) != null) { + joiner.add((({{{items.dataType}}})getActualInstance()).get(_key).toUrlQueryString(String.format(java.util.Locale.ROOT, "%s{{baseName}}%s%s", prefix, suffix, + "".equals(suffix) ? "" : String.format(java.util.Locale.ROOT, "%s%d%s", containerPrefix, _key, containerSuffix)))); + } + } + } + {{/items.isPrimitiveType}} + {{/isMap}} + {{^isMap}} + {{#isPrimitiveType}} + if (getActualInstance() != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, ApiClient.urlEncode(String.valueOf(getActualInstance())))); + } + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isModel}} + if (getActualInstance() != null) { + joiner.add((({{{dataType}}})getActualInstance()).toUrlQueryString(prefix + "{{{baseName}}}" + suffix)); + } + {{/isModel}} + {{^isModel}} + if (getActualInstance() != null) { + joiner.add(String.format(java.util.Locale.ROOT, "%s{{{baseName}}}%s=%s", prefix, suffix, ApiClient.urlEncode(String.valueOf(getActualInstance())))); + } + {{/isModel}} + {{/isPrimitiveType}} + {{/isMap}} + {{/isArray}} + return joiner.toString(); + } + {{/vendorExtensions.x-duplicated-data-type}} + {{/composedSchemas.oneOf}} + return null; + } +{{/supportUrlQuery}} + +{{#isGson}} + /** + * Create an instance of {{classname}} given an JSON string + * + * @param jsonString JSON string + * @return An instance of {{classname}} + * @throws IOException if the JSON string is invalid with respect to {{classname}} + */ + public static {{{classname}}} fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, {{{classname}}}.class); + } + + /** + * Convert an instance of {{classname}} to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +{{/isGson}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/pojo.mustache new file mode 100644 index 000000000000..4c72b698f4d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/pojo.mustache @@ -0,0 +1,1212 @@ +{{#isGson}} +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +{{! TypeAdapter, JsonReader, JsonWriter, JsonAdapter and SerializedName are contributed via + model.imports by JavaClientCodegen (postProcessModelProperty and fromModel); emitting them + here as well produced duplicate import lines. }} +{{/isGson}} +{{#isJackson}} +{{! JsonCreator, JsonInclude, JsonProperty, JsonValue and JsonTypeName are contributed via + model.imports by JavaClientCodegen.postProcessModelProperty; emitting them here as well + produced duplicate import lines. }} +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +{{#isAdditionalPropertiesTrue}} +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; +{{/isAdditionalPropertiesTrue}} +{{/isJackson}} +{{#isJsonb}} +import jakarta.json.bind.annotation.JsonbProperty; +{{#hasEnums}} +import jakarta.json.bind.adapter.JsonbAdapter; +{{/hasEnums}} +{{#isAdditionalPropertiesTrue}} +{{^vendorExtensions.x-inherits-additional-properties}} +import jakarta.json.bind.annotation.JsonbTransient; +{{/vendorExtensions.x-inherits-additional-properties}} +{{/isAdditionalPropertiesTrue}} +{{#hasEnums}} +import jakarta.json.bind.annotation.JsonbTypeAdapter; +{{/hasEnums}} +{{#hasChildren}} +import jakarta.json.JsonObject; +import jakarta.json.bind.JsonbException; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import java.lang.reflect.Type; +{{/hasChildren}} +{{#isAdditionalPropertiesTrue}} +{{^hasChildren}} +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; +import jakarta.json.bind.Jsonb; +import jakarta.json.bind.JsonbException; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import java.lang.reflect.Type; +{{/hasChildren}} +{{/isAdditionalPropertiesTrue}} +{{^isAdditionalPropertiesTrue}} +{{^hasChildren}} +{{#allVars}} +{{#-first}} +import jakarta.json.JsonObject; +import jakarta.json.JsonValue; +import jakarta.json.bind.Jsonb; +import jakarta.json.bind.JsonbException; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.stream.JsonParser; +import java.lang.reflect.Type; +{{/-first}} +{{/allVars}} +{{/hasChildren}} +{{/isAdditionalPropertiesTrue}} +{{/isJsonb}} +{{! java.io.IOException, java.util.Arrays, java.util.HashMap, java.util.Map and (for Gson) + java.util.List and java.util.Set are contributed via model.imports by + JavaClientCodegen.fromModel, which is also where codegen imports them for container + properties. Emitting them here as well produced duplicate import lines. HashSet stays: it + has no Java importMapping entry, and it is not duplicated. }} +{{^isJackson}} +import java.util.HashSet; +{{/isJackson}} +{{#isGson}} + +import {{invokerPackage}}.JSON; +{{/isGson}} +{{#isJsonb}} + +import {{invokerPackage}}.JSON; +{{/isJsonb}} + +/** + * {{description}}{{^description}}{{classname}}{{/description}}{{#isDeprecated}} + * @deprecated{{/isDeprecated}} + */{{#isDeprecated}} +@Deprecated{{/isDeprecated}} +{{#swagger1AnnotationLibrary}} +{{#description}} +@ApiModel(description = "{{{.}}}") +{{/description}} +{{/swagger1AnnotationLibrary}} +{{#swagger2AnnotationLibrary}} +{{#description}} +@Schema(description = "{{{.}}}") +{{/description}} +{{/swagger2AnnotationLibrary}} +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}} +{{#vendorExtensions.x-class-extra-annotation}} +{{{.}}} +{{/vendorExtensions.x-class-extra-annotation}} +{{#isJackson}} +@JsonPropertyOrder({ +{{#vars}} + {{classname}}.JSON_PROPERTY_{{nameInSnakeCase}}{{^-last}},{{/-last}} +{{/vars}} +}) +{{! The models/model wrapper resolves the model name even when this template is rendered + directly as a user-defined Model template ("files" config), where the bundle root's + "name" key holds the generator name instead. The bundle always carries one model. }} +@JsonTypeName("{{#models}}{{#model}}{{name}}{{/model}}{{/models}}") +{{/isJackson}} +public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{#-last}} {{/-last}}{{/vendorExtensions.x-implements}}{ +{{#serializableModel}} + private static final long serialVersionUID = 1L; + +{{/serializableModel}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} + {{^vendorExtensions.x-enum-as-string}} +{{>modelInnerEnum}} + + {{/vendorExtensions.x-enum-as-string}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} +{{>modelInnerEnum}} + + {{/mostInnerItems}} + {{/isContainer}} + {{/isEnum}} + {{#isGson}} + public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}"; + {{/isGson}} + {{#isJackson}} + public static final String JSON_PROPERTY_{{nameInSnakeCase}} = "{{baseName}}"; + {{/isJackson}} + {{#isJsonb}} + public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}"; + {{/isJsonb}} + {{#withXml}} + @Xml{{#isXmlAttribute}}Attribute{{/isXmlAttribute}}{{^isXmlAttribute}}Element{{/isXmlAttribute}}(name = "{{items.xmlName}}{{^items.xmlName}}{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}{{/items.xmlName}}"{{#xmlNamespace}}, namespace = "{{.}}"{{/xmlNamespace}}) + {{#isXmlWrapped}} + @XmlElementWrapper(name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}"{{#xmlNamespace}}, namespace = "{{.}}"{{/xmlNamespace}}) + {{/isXmlWrapped}} + {{/withXml}} + {{#deprecated}} + @Deprecated + {{/deprecated}} + {{#isGson}} + @SerializedName(SERIALIZED_NAME_{{nameInSnakeCase}}) + {{#legacyDates}} + {{#isDate}} + {{! See JSON.DateOnlyTypeAdapter: under dateLibrary=legacy a `format: date` property is a + java.util.Date, indistinguishable by type from a `format: date-time` one, so the + date-only representation has to be selected per property. }} + @com.google.gson.annotations.JsonAdapter({{invokerPackage}}.JSON.DateOnlyTypeAdapter.class) + {{/isDate}} + {{/legacyDates}} + {{/isGson}} + {{#isJackson}} + {{! No `access = ...` here: Jackson's Access.READ_ONLY means "serialize out, ignore on input", + which is the SERVER reading of OpenAPI readOnly. A client must do the opposite - populate + the value FROM the response - so emitting it silently discarded every readOnly property on + deserialization. Readonly properties are instead populated through the @JsonCreator + constructor below, which is what the shared root pojo.mustache does. }} + @JsonProperty(value = JSON_PROPERTY_{{nameInSnakeCase}}) + {{#legacyDates}} + {{#isDate}} + {{! Under dateLibrary=legacy a `format: date` property is a java.util.Date, indistinguishable + by type from a `format: date-time` one, so the mapper-wide RFC3339 date format rendered it + as a full UTC instant - both appending a time component and shifting the calendar day + backwards at positive UTC offsets. Pin the date-only pattern per property instead. + jackson-annotations stays under com.fasterxml.jackson for Jackson 3 too. }} + {{! See JSON.DateOnlySerializer - a bare @JsonFormat pattern is not enough, because with no + explicit timezone it resolves against the mapper default (UTC in Jackson, NOT the JVM + zone) and keeps shifting the day. }} + @{{jacksonPackage}}.databind.annotation.JsonSerialize(using = {{invokerPackage}}.JSON.DateOnlySerializer.class) + @{{jacksonPackage}}.databind.annotation.JsonDeserialize(using = {{invokerPackage}}.JSON.DateOnlyDeserializer.class) + {{/isDate}} + {{/legacyDates}} + {{#includeIfNull}} + @JsonInclude(value = JsonInclude.Include.ALWAYS) + {{/includeIfNull}} + {{/isJackson}} + {{#isJsonb}} + @JsonbProperty(SERIALIZED_NAME_{{nameInSnakeCase}}) + {{#legacyDates}} + {{#isDate}} + {{! See JSON.DateOnlyJsonbAdapter - same per-property selection as the Gson path. }} + @jakarta.json.bind.annotation.JsonbTypeAdapter({{invokerPackage}}.JSON.DateOnlyJsonbAdapter.class) + {{/isDate}} + {{/legacyDates}} + {{/isJsonb}} + {{#vendorExtensions.x-field-extra-annotation}} + {{{.}}} + {{/vendorExtensions.x-field-extra-annotation}} + {{>nullable_var_annotations}}{{! prevent indent}} + {{#isDiscriminator}}protected{{/isDiscriminator}}{{^isDiscriminator}}private{{/isDiscriminator}} {{>nullableDatatypeWithEnum}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + + {{/vars}} + public {{classname}}() { + {{#parent}} + {{#parcelableModel}} + super(); + {{/parcelableModel}} + {{/parent}} + {{#discriminator}} + {{#discriminator.isEnum}} +{{#readWriteVars}}{{#isDiscriminator}}{{#defaultValue}} + this.{{name}} = {{defaultValue}}; +{{/defaultValue}}{{/isDiscriminator}}{{/readWriteVars}} + {{/discriminator.isEnum}} + {{^discriminator.isEnum}} + this.{{{discriminatorName}}} = this.getClass().getSimpleName(); + {{/discriminator.isEnum}} + {{/discriminator}} + } + {{#vendorExtensions.x-has-readonly-properties}} + {{^withXml}} + + /** + * Constructor with only readonly parameters + */ + {{! @JsonCreator is required, not decorative: readonly properties get no setter (the setter + block below is guarded on the inverted isReadOnly section) and Jackson does not + auto-detect private fields, so without an annotated creator there is no path to + populate a readonly property from a response. }} + {{#isJackson}} + @JsonCreator + {{/isJackson}} + public {{classname}}( + {{#readOnlyVars}} + {{#isJackson}}@JsonProperty(value = JSON_PROPERTY_{{nameInSnakeCase}}) {{/isJackson}}{{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + this(); + {{#readOnlyVars}} + this.{{name}} = {{name}}; + {{/readOnlyVars}} + } + {{/withXml}} + {{/vendorExtensions.x-has-readonly-properties}} +{{#vendorExtensions.x-java-all-args-constructor}} + + /** + * Constructor with all args parameters + */ + public {{classname}}({{#vendorExtensions.x-java-all-args-constructor-vars}}{{>nullableArgumentWithEnum}} {{name}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-java-all-args-constructor-vars}}) { + {{#parent}} + super({{#parentVars}}{{name}}{{^-last}}, {{/-last}}{{/parentVars}}); + {{/parent}} + {{#vars}} + this.{{name}} = {{name}}; + {{/vars}} + } +{{/vendorExtensions.x-java-all-args-constructor}} + {{#vars}} + + {{^isReadOnly}} + {{#deprecated}} + @Deprecated + {{/deprecated}} + public {{classname}} {{name}}({{>nullableArgumentWithEnum}} {{name}}) { + this.{{name}} = {{name}}; + return this; + } + {{#isArray}} + + public {{classname}} add{{nameInPascalCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + if (this.{{name}} == null) { + this.{{name}} = new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(); + } + this.{{name}}.add({{name}}Item); + return this; + } + {{/isArray}} + {{#isMap}} + + public {{classname}} put{{nameInPascalCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + if (this.{{name}} == null) { + this.{{name}} = new HashMap<>(); + } + this.{{name}}.put(key, {{name}}Item); + return this; + } + {{/isMap}} + + {{/isReadOnly}} + /** + {{#description}} + * {{.}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + {{#deprecated}} + * @deprecated + {{/deprecated}} + */ +{{#deprecated}} + @Deprecated +{{/deprecated}} + {{>nullable_var_annotations}}{{! prevent indent}} +{{#useBeanValidation}} +{{>beanValidation}} + +{{/useBeanValidation}} +{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{/swagger1AnnotationLibrary}} +{{#swagger2AnnotationLibrary}} + @Schema({{#example}}example = "{{{.}}}", {{/example}}requiredMode = {{#required}}Schema.RequiredMode.REQUIRED{{/required}}{{^required}}Schema.RequiredMode.NOT_REQUIRED{{/required}}, description = "{{{description}}}") +{{/swagger2AnnotationLibrary}} +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} +{{#jackson}}{{> jackson_annotations}}{{/jackson}} + public {{>nullableDatatypeWithEnum}} {{getter}}() { + return {{name}}; + } + + {{^isReadOnly}} +{{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} +{{/vendorExtensions.x-setter-extra-annotation}}{{#deprecated}} @Deprecated +{{/deprecated}}{{#jackson}}{{> jackson_annotations}}{{/jackson}} public void {{setter}}({{>nullableArgumentWithEnum}} {{name}}) { + this.{{name}} = {{name}}; + } + {{/isReadOnly}} + + {{/vars}} +{{>additional_properties}} + + + @Override + public boolean equals(Object o) { + {{#useReflectionEqualsHashCode}} + return EqualsBuilder.reflectionEquals(this, o, false, null, true); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && + {{/-last}}{{/vars}}{{#isAdditionalPropertiesTrue}}{{^vendorExtensions.x-inherits-additional-properties}}&& + Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/vendorExtensions.x-inherits-additional-properties}}{{/isAdditionalPropertiesTrue}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} + {{/useReflectionEqualsHashCode}} + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + 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())); + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} + + @Override + public int hashCode() { + {{#useReflectionEqualsHashCode}} + return HashCodeBuilder.reflectionHashCode(this); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#isAdditionalPropertiesTrue}}{{^vendorExtensions.x-inherits-additional-properties}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/vendorExtensions.x-inherits-additional-properties}}{{/isAdditionalPropertiesTrue}}); + {{/useReflectionEqualsHashCode}} + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}} + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + {{/parent}} + {{#vars}} + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); + {{/vars}} +{{#isAdditionalPropertiesTrue}} +{{^vendorExtensions.x-inherits-additional-properties}} + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); +{{/vendorExtensions.x-inherits-additional-properties}} +{{/isAdditionalPropertiesTrue}} + 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) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + +{{#parcelableModel}} + + public void writeToParcel(Parcel out, int flags) { +{{#model}} +{{#isArray}} + out.writeList(this); +{{/isArray}} +{{^isArray}} +{{#parent}} + super.writeToParcel(out, flags); +{{/parent}} +{{#vars}} + out.writeValue({{name}}); +{{/vars}} +{{/isArray}} +{{/model}} + } + + {{classname}}(Parcel in) { +{{#isArray}} + in.readTypedList(this, {{arrayModelType}}.CREATOR); +{{/isArray}} +{{^isArray}} +{{#parent}} + super(in); +{{/parent}} +{{#vars}} +{{#isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); +{{/isPrimitiveType}} +{{^isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); +{{/isPrimitiveType}} +{{/vars}} +{{/isArray}} + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { + public {{classname}} createFromParcel(Parcel in) { +{{#model}} +{{#isArray}} + {{classname}} result = new {{classname}}(); + result.addAll(in.readArrayList({{arrayModelType}}.class.getClassLoader())); + return result; +{{/isArray}} +{{^isArray}} + return new {{classname}}(in); +{{/isArray}} +{{/model}} + } + public {{classname}}[] newArray(int size) { + return new {{classname}}[size]; + } + }; +{{/parcelableModel}} + + {{^isJackson}} + {{! Jackson binds through annotations and never consults these sets; the Gson TypeAdapter and the + JSON-B deserializer use them for required/undeclared-field validation. }} + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + {{! the set is filled from allVars, so it has to be guarded on allVars too: a pure allOf + refinement declares no property of its own but still inherits every declared property, + and an empty set here makes every consumer treat a declared field as an undeclared one }} + {{#allVars}} + {{#-first}} + openapiFields = new HashSet(Arrays.asList({{#allVars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/allVars}})); + {{/-first}} + {{/allVars}} + {{^allVars}} + openapiFields = new HashSet(0); + {{/allVars}} + + // a set of required properties/fields (JSON key names) + {{#hasRequired}} + openapiRequiredFields = new HashSet(Arrays.asList({{#requiredVars}}"{{baseName}}"{{^-last}}, {{/-last}}{{/requiredVars}})); + {{/hasRequired}} + {{^hasRequired}} + openapiRequiredFields = new HashSet(0); + {{/hasRequired}} + } + {{/isJackson}} + +{{#isGson}} + /** + * 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 {{classname}} + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!{{classname}}.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in {{{classname}}} is not found in the empty JSON string", {{classname}}.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + {{^hasChildren}} + {{^isAdditionalPropertiesTrue}} + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!{{classname}}.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` in the JSON string is not defined in the `{{classname}}` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + {{/isAdditionalPropertiesTrue}} + {{#requiredVars}} + {{#-first}} + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : {{classname}}.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + {{/-first}} + {{/requiredVars}} + {{/hasChildren}} + {{^discriminator}} + {{! allVars, like openapiRequiredFields above: a child model enforces its parent's + `not: enum` constraints too. }} + {{#allVars}} + {{#vendorExtensions.x-java-not-string-enum-values}} + if (jsonElement.getAsJsonObject().get("{{{baseName}}}") instanceof com.google.gson.JsonPrimitive + && jsonElement.getAsJsonObject().getAsJsonPrimitive("{{{baseName}}}").isString() + && {{#lambda.javaStringLiteral}}{{{.}}}{{/lambda.javaStringLiteral}}.equals(jsonElement.getAsJsonObject().get("{{{baseName}}}").getAsString())) { + throw new IllegalArgumentException(String.format( + java.util.Locale.ROOT, + "The field `{{{baseName}}}` in the JSON string matches a value disallowed by `not`: `%s`", + jsonElement.getAsJsonObject().get("{{{baseName}}}").toString())); + } + {{/vendorExtensions.x-java-not-string-enum-values}} + {{/allVars}} + {{#hasVars}} + JsonObject jsonObj = jsonElement.getAsJsonObject(); + {{/hasVars}} + {{#vars}} + {{#isArray}} + {{#items.isModel}} + {{#required}} + if (jsonObj.get("{{{baseName}}}") != null{{#isNullable}} && !jsonObj.get("{{{baseName}}}").isJsonNull(){{/isNullable}}) { + if (!jsonObj.get("{{{baseName}}}").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); + } + com.google.gson.JsonArray jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}"); + // validate the required field `{{{baseName}}}` (array) + for (int i = 0; i < jsonArray{{name}}.size(); i++) { + {{{items.dataType}}}.validateJsonElement(jsonArray{{name}}.get(i)); + } + } + {{/required}} + {{^required}} + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + com.google.gson.JsonArray jsonArray{{name}} = jsonObj.getAsJsonArray("{{{baseName}}}"); + if (jsonArray{{name}} != null) { + // ensure the json data is an array + if (!jsonObj.get("{{{baseName}}}").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); + } + + // validate the optional field `{{{baseName}}}` (array) + for (int i = 0; i < jsonArray{{name}}.size(); i++) { + {{{items.dataType}}}.validateJsonElement(jsonArray{{name}}.get(i)); + }; + } + } + {{/required}} + {{/items.isModel}} + {{^items.isModel}} + {{^required}} + // ensure the optional json data is an array if present + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull() && !jsonObj.get("{{{baseName}}}").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); + } + {{/required}} + {{#required}} + // ensure the required json array is present + if (jsonObj.get("{{{baseName}}}") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("{{{baseName}}}").isJsonArray(){{#isNullable}} && !jsonObj.get("{{baseName}}").isJsonNull(){{/isNullable}}) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); + } + {{/required}} + {{/items.isModel}} + {{/isArray}} + {{^isContainer}} + {{#isString}} + if ({{#notRequiredOrIsNullable}}(jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) && {{/notRequiredOrIsNullable}}!jsonObj.get("{{{baseName}}}").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `{{{baseName}}}` to be a primitive type in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString())); + } + {{/isString}} + {{#isModel}} + {{^isEnum}} + {{#required}} + {{#isNullable}} + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{/isNullable}} + // validate the required field `{{{baseName}}}` + {{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + {{#isNullable}} + } + {{/isNullable}} + {{/required}} + {{^required}} + // validate the optional field `{{{baseName}}}` + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + } + {{/required}} + {{/isEnum}} + {{/isModel}} + {{#isEnum}} + {{#required}} + {{#isNullable}} + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{/isNullable}} + // validate the required field `{{{baseName}}}` + {{{datatypeWithEnum}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + {{#isNullable}} + } + {{/isNullable}} + {{/required}} + {{^required}} + // validate the optional field `{{{baseName}}}` + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{{datatypeWithEnum}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + } + {{/required}} + {{/isEnum}} + {{#isEnumRef}} + {{#required}} + {{#isNullable}} + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{/isNullable}} + // validate the required field `{{{baseName}}}` + {{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + {{#isNullable}} + } + {{/isNullable}} + {{/required}} + {{^required}} + // validate the optional field `{{{baseName}}}` + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + } + {{/required}} + {{/isEnumRef}} + {{/isContainer}} + {{/vars}} + {{/discriminator}} + {{#hasChildren}} + {{#discriminator}} + + String discriminatorValue = jsonElement.getAsJsonObject().get("{{{propertyBaseName}}}").getAsString(); + switch (discriminatorValue) { + {{#mappedModels}} + case "{{mappingName}}": + {{modelName}}.validateJsonElement(jsonElement); + break; + {{/mappedModels}} + default: + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The value of the `{{{propertyBaseName}}}` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue)); + } + {{/discriminator}} + {{/hasChildren}} + } + +{{^hasChildren}} + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!{{classname}}.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes '{{classname}}' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter<{{classname}}> thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get({{classname}}.class)); + + return (TypeAdapter) new TypeAdapter<{{classname}}>() { + @Override + public void write(JsonWriter out, {{classname}} value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + {{#isAdditionalPropertiesTrue}} + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + {{/isAdditionalPropertiesTrue}} + elementAdapter.write(out, obj); + } + + @Override + public {{classname}} read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + {{#isAdditionalPropertiesTrue}} + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + {{classname}} instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + {{/isAdditionalPropertiesTrue}} + {{^isAdditionalPropertiesTrue}} + return thisAdapter.fromJsonTree(jsonElement); + {{/isAdditionalPropertiesTrue}} + } + + }.nullSafe(); + } + } +{{/hasChildren}} +{{/isGson}} + +{{#isGson}} + /** + * Create an instance of {{classname}} given an JSON string + * + * @param jsonString JSON string + * @return An instance of {{classname}} + * @throws IOException if the JSON string is invalid with respect to {{classname}} + */ + public static {{{classname}}} fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, {{{classname}}}.class); + } + + /** + * Convert an instance of {{classname}} to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +{{/isGson}} +{{#isJsonb}} +{{#hasChildren}} +{{! A parent without a discriminator (x-parent, or a single allOf $ref) needs these too: the + leaf (de)serializers below are skipped for every model with children, and Yasson falls + back to a superclass' serializer, so only this delegating variant is safe for a parent. + With no discriminator the deserializer simply binds the root itself. }} + + /** + * Custom JSON-B serializer for the root of a discriminated hierarchy. Yasson serializes a + * value against its declared type, which would drop every subtype field, and its native + * polymorphism support (JsonbTypeInfo) rejects hierarchies whose discriminator is also a + * bean property. Delegating to the polymorphism-free Jsonb instance serializes the runtime + * type with all of its fields; the discriminator value is carried by the property itself. + */ + public static class CustomJsonbSerializer implements JsonbSerializer<{{classname}}> { + @Override + public void serialize({{classname}} value, JsonGenerator generator, SerializationContext context) { + {{^isAdditionalPropertiesTrue}} + generator.write(toJsonValue(value)); + {{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + JsonObject serialized = toJsonValue(value).asJsonObject(); + {{! The polymorphism-free instance carries no serializer for this class, so a value whose + runtime type is this root is written by plain bean mapping and the @JsonbTransient + additional-properties holder is dropped. A subtype was already flattened by its own + serializer, and the declared-name guard leaves that output untouched. }} + if (value.getAdditionalProperties() != null) { + java.util.Set declaredFields = declaredFields(value); + jakarta.json.JsonObjectBuilder builder = jakarta.json.Json.createObjectBuilder(serialized); + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + // a declared property always wins over an additional property with the same name + if (declaredFields.contains(entry.getKey()) || serialized.containsKey(entry.getKey())) { + continue; + } + if (entry.getValue() == null) { + builder.addNull(entry.getKey()); + } else { + builder.add(entry.getKey(), toNestedJsonValue(entry.getValue())); + } + } + serialized = builder.build(); + } + generator.write(serialized); + {{/isAdditionalPropertiesTrue}} + } + {{#isAdditionalPropertiesTrue}} + + /** + * The declared property names of the value's runtime type. A subtype serializer omits a + * declared property whose value is null, so the serialized object alone cannot tell whether + * a name is declared; consulting the runtime type keeps an additional property from being + * written under a subtype's declared name. Falls back to this class' own names for a + * runtime type that is not a mapped subtype. + */ + private static java.util.Set declaredFields({{classname}} value) { + {{#discriminator.mappedModels}} + {{#model}} + if ({{modelName}}.class.equals(value.getClass())) { + return {{modelName}}.openapiFields; + } + {{/model}} + {{/discriminator.mappedModels}} + return openapiFields; + } + {{/isAdditionalPropertiesTrue}} + + /** + * Render a value through the polymorphism-free Jsonb and read it back as a JsonValue. + */ + private static jakarta.json.JsonValue toJsonValue(Object value) { + try (jakarta.json.JsonReader reader = jakarta.json.Json.createReader( + new java.io.StringReader(JSON.getPlainJsonb().toJson(value)))) { + return reader.readValue(); + } + } + {{#isAdditionalPropertiesTrue}} + + /** + * Render an additional-property value through the configured Jsonb and read it back as a + * JsonValue. A nested value is a different object from the one being serialized here, so + * this cannot re-enter the serializer currently in hand; the polymorphism-free instance + * carries no serializer for a hierarchy root, and using it here would drop the additional + * properties of a nested value whose runtime type is one. + */ + private static jakarta.json.JsonValue toNestedJsonValue(Object value) { + try (jakarta.json.JsonReader reader = jakarta.json.Json.createReader( + new java.io.StringReader(JSON.getJsonb().toJson(value)))) { + return reader.readValue(); + } + } + {{/isAdditionalPropertiesTrue}} + } + + /** + * Custom JSON-B deserializer for the root of a discriminated hierarchy: picks the subtype + * from the discriminator value the way the Gson variant's TypeSelector does. Binding goes + * through the polymorphism-free Jsonb instance so this deserializer cannot recurse into + * itself. + */ + public static class CustomJsonbDeserializer implements JsonbDeserializer<{{classname}}> { + @Override + public {{classname}} deserialize(JsonParser parser, DeserializationContext context, Type rtType) { + JsonObject jsonObj = parser.getObject(); + {{#discriminator}} + String discriminatorValue = jsonObj.getString("{{{discriminator.propertyBaseName}}}", null); + {{/discriminator}} + {{#discriminator.mappedModels}} + if ("{{mappingName}}".equals(discriminatorValue)) { + {{#model}} + {{#hasChildren}} + {{! A subtype that has children of its own is itself a hierarchy root, so it carries no + required-field deserializer on any Jsonb instance; check its required properties + here, the way the deserializer of a leaf subtype would. }} + validateRequiredFields(jsonObj, {{modelName}}.openapiRequiredFields, "{{modelName}}"); + {{#isAdditionalPropertiesTrue}} + {{! This subtype has children of its own, so the polymorphism-free instance carries no + additional-properties deserializer for it either and would discard its undeclared + keys; collect them the way its own deserializer does. }} + {{modelName}} mapped = JSON.getPlainJsonb().fromJson(jsonObj.toString(), {{modelName}}.class); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!{{modelName}}.openapiFields.contains(entry.getKey())) { + mapped.putAdditionalProperty(entry.getKey(), + entry.getValue().getValueType() == jakarta.json.JsonValue.ValueType.NULL + ? null + : JSON.getPlainJsonb().fromJson(entry.getValue().toString(), Object.class)); + } + } + return mapped; + {{/isAdditionalPropertiesTrue}} + {{^isAdditionalPropertiesTrue}} + return JSON.getPlainJsonb().fromJson(jsonObj.toString(), {{modelName}}.class); + {{/isAdditionalPropertiesTrue}} + {{/hasChildren}} + {{^hasChildren}} + return JSON.getPlainJsonb().fromJson(jsonObj.toString(), {{modelName}}.class); + {{/hasChildren}} + {{/model}} + {{^model}} + return JSON.getPlainJsonb().fromJson(jsonObj.toString(), {{modelName}}.class); + {{/model}} + } + {{/discriminator.mappedModels}} + {{! The discriminator value matches no mapping, so the payload binds as the root itself. + The root has children, so it carries no required-field deserializer either. }} + validateRequiredFields(jsonObj, openapiRequiredFields, "{{classname}}"); + {{^isAdditionalPropertiesTrue}} + return JSON.getPlainJsonb().fromJson(jsonObj.toString(), {{classname}}.class); + {{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + {{! Binding the root itself goes through plain bean mapping, which cannot see the + @JsonbTransient additional-properties holder and silently discards every undeclared + key. Collect them here, mirroring the flattening the serializer above performs. }} + {{classname}} instance = JSON.getPlainJsonb().fromJson(jsonObj.toString(), {{classname}}.class); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + instance.putAdditionalProperty(entry.getKey(), + entry.getValue().getValueType() == jakarta.json.JsonValue.ValueType.NULL + ? null + : JSON.getPlainJsonb().fromJson(entry.getValue().toString(), Object.class)); + } + } + return instance; + {{/isAdditionalPropertiesTrue}} + } + + /** + * Reject a JSON object that does not carry every required property of the target model. + * Used for the models of this hierarchy that have children of their own: they bind by + * plain bean mapping, which has no notion of a required property, and - unlike a leaf + * subtype - they carry no required-field deserializer of their own. + */ + private static void validateRequiredFields(JsonObject jsonObj, java.util.Set requiredFields, String modelName) { + for (String requiredField : requiredFields) { + if (!jsonObj.containsKey(requiredField)) { + throw new JsonbException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON object for `%s`: %s", requiredField, modelName, jsonObj)); + } + } + } + } +{{/hasChildren}} +{{#isAdditionalPropertiesTrue}} +{{^hasChildren}} + + /** + * Custom JSON-B serializer that flattens the additional (undeclared) properties into the + * serialized object. JSON-B has no equivalent of Jackson's {@code @JsonAnyGetter}, so without + * this serializer values added through {@code putAdditionalProperty} would not be emitted + * under their original names. Registered with the Jsonb instance built by {@code JSON}. + */ + public static class CustomJsonbSerializer implements JsonbSerializer<{{classname}}> { + @Override + public void serialize({{classname}} value, JsonGenerator generator, SerializationContext context) { + generator.writeStartObject(); + {{#allVars}} + if (value.{{getter}}() != null) { + context.serialize("{{baseName}}", value.{{getter}}(), generator); + } + {{/allVars}} + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + // a declared property always wins over an additional property with the same name + if (!openapiFields.contains(entry.getKey())) { + // SerializationContext.serialize rejects a null value, so write the JSON null here + if (entry.getValue() == null) { + generator.writeNull(entry.getKey()); + } else { + context.serialize(entry.getKey(), entry.getValue(), generator); + } + } + } + } + generator.writeEnd(); + } + } + + /** + * Custom JSON-B deserializer that captures undeclared fields into the additional-properties + * map. JSON-B has no equivalent of Jackson's {@code @JsonAnySetter}, so without this + * deserializer unknown response keys would be silently dropped. Registered with the Jsonb + * instance built by {@code JSON}. + */ + public static class CustomJsonbDeserializer implements JsonbDeserializer<{{classname}}> { + @Override + public {{classname}} deserialize(JsonParser parser, DeserializationContext context, Type rtType) { + JsonObject jsonObj = parser.getObject(); + for (String requiredField : openapiRequiredFields) { + if (!jsonObj.containsKey(requiredField)) { + throw new JsonbException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON object: %s", requiredField, jsonObj)); + } + } + // capture once so every field of this object binds against the same configuration, + // even if a format setter rebuilds the shared instance concurrently + {{#allVars}} + {{#vendorExtensions.x-java-not-string-enum-values}} + if (jsonObj.get("{{{baseName}}}") instanceof jakarta.json.JsonString + && {{#lambda.javaStringLiteral}}{{{.}}}{{/lambda.javaStringLiteral}}.equals(((jakarta.json.JsonString) jsonObj.get("{{{baseName}}}")).getString())) { + throw new JsonbException(String.format(java.util.Locale.ROOT, "The field `{{{baseName}}}` in the JSON object matches a value disallowed by `not`: %s", jsonObj.get("{{{baseName}}}"))); + } + {{/vendorExtensions.x-java-not-string-enum-values}} + {{/allVars}} + Jsonb jsonb = JSON.getJsonb(); + {{classname}} instance = new {{classname}}(); + {{#allVars}} + if (jsonObj.containsKey("{{baseName}}")) { + {{^isReadOnly}} + instance.{{setter}}(jsonObj.get("{{baseName}}").getValueType() == JsonValue.ValueType.NULL + ? null + : {{#isDate}}{{#legacyDates}}JSON.dateOnlyFromJson(jsonObj.get("{{baseName}}")){{/legacyDates}}{{^legacyDates}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/legacyDates}}{{/isDate}}{{^isDate}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/isDate}}); + {{/isReadOnly}} + {{#isReadOnly}} + // readOnly properties have no setter; bind the declared field directly + setField(instance, "{{name}}", jsonObj.get("{{baseName}}").getValueType() == JsonValue.ValueType.NULL + ? null + : {{#isDate}}{{#legacyDates}}JSON.dateOnlyFromJson(jsonObj.get("{{baseName}}")){{/legacyDates}}{{^legacyDates}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/legacyDates}}{{/isDate}}{{^isDate}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/isDate}}); + {{/isReadOnly}} + } + {{/allVars}} + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + instance.putAdditionalProperty(entry.getKey(), + entry.getValue().getValueType() == JsonValue.ValueType.NULL + ? null + : jsonb.fromJson(entry.getValue().toString(), Object.class)); + } + } + return instance; + } + + private static java.lang.reflect.Field declaredField(String fieldName) { + // walk up the hierarchy: inherited properties are declared on a parent class + for (Class clazz = {{classname}}.class; clazz != null; clazz = clazz.getSuperclass()) { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + // not declared on this class; check the parent + } + } + throw new IllegalArgumentException("Field " + fieldName + " not found on {{classname}}"); + } + + private static Type fieldType(String fieldName) { + return declaredField(fieldName).getGenericType(); + } + + private static void setField({{classname}} instance, String fieldName, Object value) { + try { + java.lang.reflect.Field field = declaredField(fieldName); + field.setAccessible(true); + field.set(instance, value); + } catch (IllegalAccessException e) { + throw new JsonbException("Unable to bind the field " + fieldName + " on {{classname}}", e); + } + } + } +{{/hasChildren}} +{{/isAdditionalPropertiesTrue}} +{{^isAdditionalPropertiesTrue}} +{{^hasChildren}} +{{#allVars}} +{{#-first}} + + /** + * Custom JSON-B deserializer for a model that forbids additional properties: it rejects a + * JSON object carrying an undeclared field or missing a required one. Yasson binds such a + * model by plain bean mapping, which silently drops an unknown key and has no notion of a + * required property, so without this deserializer any JSON object would bind - and an + * ambiguous {@code oneOf}/{@code anyOf} schema could not tell its branches apart. The + * checks mirror the Gson type adapter's {@code validateJsonElement}. Registered with the + * Jsonb instances built by {@code JSON}. + */ + public static class CustomJsonbDeserializer implements JsonbDeserializer<{{classname}}> { + @Override + public {{classname}} deserialize(JsonParser parser, DeserializationContext context, Type rtType) { + {{! Yasson routes a JSON null through the deserializer of the declared type instead of + short-circuiting it, and asJsonObject() would then fail on a payload that plain bean + mapping - and the Gson type adapter - bind as null. }} + JsonValue value = parser.getValue(); + if (value == null || value.getValueType() == JsonValue.ValueType.NULL) { + return null; + } + JsonObject jsonObj = value.asJsonObject(); + // check that the JSON object carries no field this model does not declare + for (String field : jsonObj.keySet()) { + if (!openapiFields.contains(field)) { + throw new JsonbException(String.format(java.util.Locale.ROOT, "The field `%s` in the JSON object is not defined in the `{{classname}}` properties. JSON: %s", field, jsonObj)); + } + } + {{! containsKey, not a null check on the value: a required property that is present but + explicitly null passes here, exactly as it does in the additional-properties + deserializer above and in the Gson type adapter's required-field loop. }} + for (String requiredField : openapiRequiredFields) { + if (!jsonObj.containsKey(requiredField)) { + throw new JsonbException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON object: %s", requiredField, jsonObj)); + } + } + {{! Bind property by property rather than handing the whole object back to a Jsonb + instance: a whole-object bind would have to go through an instance that carries no + required-field checker at all - which then skips the checks of every NESTED model + too. Binding each property through the fully configured instance cannot re-enter + this deserializer (the target type is the property's, not this class') and keeps a + nested model's own checks, discriminated-subtype dispatch and additional-properties + capture in place. }} + // capture once so every field of this object binds against the same configuration, + // even if a format setter rebuilds the shared instance concurrently + {{#allVars}} + {{#vendorExtensions.x-java-not-string-enum-values}} + if (jsonObj.get("{{{baseName}}}") instanceof jakarta.json.JsonString + && {{#lambda.javaStringLiteral}}{{{.}}}{{/lambda.javaStringLiteral}}.equals(((jakarta.json.JsonString) jsonObj.get("{{{baseName}}}")).getString())) { + throw new JsonbException(String.format(java.util.Locale.ROOT, "The field `{{{baseName}}}` in the JSON object matches a value disallowed by `not`: %s", jsonObj.get("{{{baseName}}}"))); + } + {{/vendorExtensions.x-java-not-string-enum-values}} + {{/allVars}} + Jsonb jsonb = JSON.getJsonb(); + {{classname}} instance = new {{classname}}(); + {{#allVars}} + if (jsonObj.containsKey("{{baseName}}")) { + {{^isReadOnly}} + instance.{{setter}}(jsonObj.get("{{baseName}}").getValueType() == JsonValue.ValueType.NULL + ? null + : {{#isDate}}{{#legacyDates}}JSON.dateOnlyFromJson(jsonObj.get("{{baseName}}")){{/legacyDates}}{{^legacyDates}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/legacyDates}}{{/isDate}}{{^isDate}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/isDate}}); + {{/isReadOnly}} + {{#isReadOnly}} + // readOnly properties have no setter; bind the declared field directly + setField(instance, "{{name}}", jsonObj.get("{{baseName}}").getValueType() == JsonValue.ValueType.NULL + ? null + : {{#isDate}}{{#legacyDates}}JSON.dateOnlyFromJson(jsonObj.get("{{baseName}}")){{/legacyDates}}{{^legacyDates}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/legacyDates}}{{/isDate}}{{^isDate}}jsonb.fromJson(jsonObj.get("{{baseName}}").toString(), fieldType("{{name}}")){{/isDate}}); + {{/isReadOnly}} + } + {{/allVars}} + return instance; + } + + private static java.lang.reflect.Field declaredField(String fieldName) { + // walk up the hierarchy: inherited properties are declared on a parent class + for (Class clazz = {{classname}}.class; clazz != null; clazz = clazz.getSuperclass()) { + try { + return clazz.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + // not declared on this class; check the parent + } + } + throw new IllegalArgumentException("Field " + fieldName + " not found on {{classname}}"); + } + + private static Type fieldType(String fieldName) { + return declaredField(fieldName).getGenericType(); + } + + private static void setField({{classname}} instance, String fieldName, Object value) { + try { + java.lang.reflect.Field field = declaredField(fieldName); + field.setAccessible(true); + field.set(instance, value); + } catch (IllegalAccessException e) { + throw new JsonbException("Unable to bind the field " + fieldName + " on {{classname}}", e); + } + } + } +{{/-first}} +{{/allVars}} +{{/hasChildren}} +{{/isAdditionalPropertiesTrue}} +{{/isJsonb}} +{{#generateBuilders}} + + {{>javaBuilder}}{{! prevent indent}} +{{/generateBuilders}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/pom.mustache new file mode 100644 index 000000000000..c244d609317e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp/pom.mustache @@ -0,0 +1,539 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} + + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} + +{{#parentOverridden}} + + {{{parentGroupId}}} + {{{parentArtifactId}}} + {{{parentVersion}}} + +{{/parentOverridden}} + + + + {{licenseName}} + {{licenseUrl}} + repo + + + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + {{#useJackson3}} + 17 + 17 + {{/useJackson3}} + {{^useJackson3}} + 1.8 + 1.8 + {{/useJackson3}} + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.4.1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + + + + + maven-dependency-plugin + 3.6.1 + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.5.0 + + + add_sources + generate-sources + + add-source + + + + {{{sourceFolder}}} + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.6.3 + + + attach-javadocs + + jar + + + + + none + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.0 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.2.1 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + com.squareup.okhttp3 + okhttp-bom + ${okhttp-version} + pom + import + + {{#isJackson}} + {{#useJackson3}} + + tools.jackson + jackson-bom + ${jackson-version} + pom + import + + {{/useJackson3}} + {{^useJackson3}} + + com.fasterxml.jackson + jackson-bom + ${jackson-version} + pom + import + + {{/useJackson3}} + {{/isJackson}} + + + + {{#swagger1AnnotationLibrary}} + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + {{/swagger1AnnotationLibrary}} + {{#swagger2AnnotationLibrary}} + + io.swagger.core.v3 + swagger-annotations + ${swagger-annotations-version} + + {{/swagger2AnnotationLibrary}} + {{^useJspecify}} + + + com.google.code.findbugs + jsr305 + 3.0.2 + + {{/useJspecify}} + {{#useJspecify}} + + org.jspecify + jspecify + 1.0.0 + + {{/useJspecify}} + + com.squareup.okhttp3 + okhttp-jvm + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + {{#isGson}} + + com.google.code.gson + gson + ${gson-version} + + + io.gsonfire + gson-fire + ${gson-fire-version} + + {{/isGson}} + {{#isJackson}} + + {{jacksonPackage}}.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + {{^useJackson3}} + ${jackson-annotations-version} + {{/useJackson3}} + + + {{jacksonPackage}}.core + jackson-databind + ${jackson-version} + + {{^useJackson3}} + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + {{/useJackson3}} + {{/isJackson}} + {{#openApiNullable}} + {{^isJsonb}} + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + {{/isJsonb}} + {{/openApiNullable}} + {{#isJsonb}} + + jakarta.json.bind + jakarta.json.bind-api + ${jsonb-api-version} + + + org.eclipse + yasson + ${yasson-version} + + + jakarta.json + jakarta.json-api + 2.1.3 + + + org.eclipse.parsson + parsson + 1.1.7 + + {{/isJsonb}} + {{#useReflectionEqualsHashCode}} + + org.apache.commons + commons-lang3 + ${commons-lang3-version} + + {{/useReflectionEqualsHashCode}} + {{#joda}} + + joda-time + joda-time + ${jodatime-version} + + {{#isJackson}} + + {{jacksonPackage}}.datatype + jackson-datatype-joda + ${jackson-version} + + {{/isJackson}} + {{/joda}} + {{#useBeanValidation}} + + + jakarta.validation + jakarta.validation-api + ${beanvalidation-version} + provided + + {{/useBeanValidation}} + {{#performBeanValidation}} + + + org.hibernate.validator + hibernate-validator + ${hibernate-validator-version} + + {{#useJakartaEe}} + + + jakarta.el + jakarta.el-api + ${jakarta.el-version} + + + org.glassfish.expressly + expressly + ${expressly-version} + + {{/useJakartaEe}} + {{^useJakartaEe}} + + + org.glassfish + jakarta.el + ${glassfish-el-version} + + {{/useJakartaEe}} + {{/performBeanValidation}} + {{#withAWSV4Signature}} + + software.amazon.awssdk + auth + 2.20.157 + + {{/withAWSV4Signature}} + {{#dynamicOperations}} + + io.swagger.parser.v3 + swagger-parser-v3 + 2.0.30 + + {{/dynamicOperations}} + {{#parcelableModel}} + + + com.google.android + android + 4.1.1.4 + provided + + {{/parcelableModel}} + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + test + + + org.junit.platform + junit-platform-runner + ${junit-platform-runner.version} + test + + + + {{#java17}}17{{/java17}}{{^java17}}{{#java11}}11{{/java11}}{{^java11}}1.8{{/java11}}{{/java17}} + ${java.version} + ${java.version} + 1.9.0 + {{#swagger1AnnotationLibrary}} + 1.6.6 + {{/swagger1AnnotationLibrary}} + {{#swagger2AnnotationLibrary}} + 2.2.15 + {{/swagger2AnnotationLibrary}} + 5.4.0 + {{#isGson}} + 2.10.1 + {{/isGson}} + {{#isJackson}} + {{#useJackson3}} + 3.2.1 + {{/useJackson3}} + {{^useJackson3}} + 2.22.1 + 2.22 + 2.22.1 + {{/useJackson3}} + {{/isJackson}} + {{#isJsonb}} + 3.0.1 + 3.0.4 + {{/isJsonb}} + {{#useReflectionEqualsHashCode}} + 3.18.0 + {{/useReflectionEqualsHashCode}} + {{#openApiNullable}} + 0.2.12 + {{/openApiNullable}} + {{#joda}} + 2.12.0 + {{/joda}} + {{#useJakartaEe}} + 2.1.1 + {{#useBeanValidation}} + 3.0.2 + {{/useBeanValidation}} + {{/useJakartaEe}} + {{^useJakartaEe}} + 1.3.5 + {{#useBeanValidation}} + 2.0.2 + {{/useBeanValidation}} + {{/useJakartaEe}} + {{#performBeanValidation}} + {{#useJakartaEe}} + 8.0.3.Final + 5.0.1 + 5.0.0 + {{/useJakartaEe}} + {{^useJakartaEe}} + 6.2.5.Final + 3.0.4 + {{/useJakartaEe}} + {{/performBeanValidation}} + 5.10.3 + 1.10.0 + UTF-8 + + diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index bfcf3d6dce31..fa4b47e324ca 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -91,7 +91,8 @@ enum Library { JERSEY_3("jersey3", Serializer.JACKSON), MICROPROFILE("microprofile", Serializer.JSONB, Set.of(Serializer.JACKSON)), NATIVE("native", Serializer.JACKSON), - OKHTTP("okhttp-gson", Serializer.GSON), + OKHTTP("okhttp", Serializer.GSON, Set.of(Serializer.JACKSON, Serializer.JSONB)), + OKHTTP_GSON("okhttp-gson", Serializer.GSON), REST_ASSURED("rest-assured", Serializer.GSON, Set.of(Serializer.JACKSON)), RESTEASY("resteasy", Serializer.JACKSON), REST_CLIENT("restclient", Serializer.JACKSON), @@ -605,6 +606,22 @@ public void testNestedArrayDefaultDoesNotSeedAddItemWithDefault() { .doesNotContainPattern("this\\.nestedArray\\s*=\\s*new\\s+ArrayList\\s*<\\s*>\\s*\\(\\s*Arrays\\.asList\\s*\\("); } + @Test + public void testNestedArrayDefaultDoesNotSeedAddItemWithDefaultOkHttp() { + final Map files = generateFromContract( + "src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml", + JavaClientCodegen.OKHTTP); + + assertThat(files.get("NestedArrayWithDefaultValues.java").toPath()).content() + .containsPattern("private\\s+List\\s*<\\s*List\\s*<\\s*String\\s*>\\s*>\\s+nestedArray\\s*=\\s*" + + "new\\s+ArrayList\\s*<\\s*>\\s*\\(\\s*Arrays\\.asList\\s*\\(\\s*" + + "new\\s+ArrayList\\s*<\\s*>\\s*\\(\\s*Arrays\\.asList\\s*\\(\\s*" + + "\\\"h1\\\"\\s*,\\s*\\\"Header 1\\\"\\s*\\)\\s*\\)\\s*,") + .containsPattern("if\\s*\\(\\s*this\\.nestedArray\\s*==\\s*null\\s*\\)\\s*\\{\\s*" + + "this\\.nestedArray\\s*=\\s*new\\s+ArrayList\\s*<\\s*>\\s*\\(\\s*\\)\\s*;") + .doesNotContainPattern("this\\.nestedArray\\s*=\\s*new\\s+ArrayList\\s*<\\s*>\\s*\\(\\s*Arrays\\.asList\\s*\\("); + } + @Test public void testJersey3NullableContainerDefaultIsDeclared() { final Map files = generateFromContract( @@ -689,6 +706,62 @@ public void testDynamicJsonContentHeaderUsesJsonSerialization() { .contains("paramMap.put(\"X-Plain-Arg\", xPlainArg);"); } + @Test + public void testJsonContentHeaderUsesJsonSerializationOkHttp() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName(JAVA_GENERATOR) + .setLibrary(JavaClientCodegen.OKHTTP) + .setInputSpec("src/test/resources/3_1/java/json-header-content.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + + assertThat(output.resolve("src/main/java/org/openapitools/client/ApiClient.java")) + .content() + .contains("public String parameterToJsonString(Object param)"); + + assertThat(output.resolve("src/main/java/org/openapitools/client/api/DefaultApi.java")) + .content() + .contains( + "localVarHeaderParams.put(\"X-Json-Arg\", localVarApiClient.parameterToJsonString(xJsonArg));" + ) + .doesNotContain( + "localVarHeaderParams.put(\"X-Json-Arg\", localVarApiClient.parameterToString(xJsonArg));" + ) + .contains( + "localVarHeaderParams.put(\"X-Plain-Arg\", localVarApiClient.parameterToString(xPlainArg));" + ); + } + + @Test + public void testDynamicJsonContentHeaderUsesJsonSerializationOkHttp() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName(JAVA_GENERATOR) + .setLibrary(JavaClientCodegen.OKHTTP) + .setInputSpec("src/test/resources/3_1/java/json-header-content.yaml") + .addAdditionalProperty("dynamicOperations", true) + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + + assertThat(output.resolve("src/main/java/org/openapitools/client/ApiClient.java")) + .content() + .contains("if (param.getContent() != null && param.getContent().containsKey(\"application/json\")) {") + .contains("headerParams.put(param.getName(), parameterToJsonString(value));") + .contains("headerParams.put(param.getName(), parameterToString(value));"); + + assertThat(output.resolve("src/main/java/org/openapitools/client/api/DefaultApi.java")) + .content() + .contains("paramMap.put(\"X-Json-Arg\", xJsonArg);") + .contains("paramMap.put(\"X-Plain-Arg\", xPlainArg);"); + } + @Test public void testGeneratePingSomeObj() { final Path output = newTempFolder(); @@ -2340,9 +2413,14 @@ public void testJdkHttpClientWithAndWithoutParentExtension() { .content().contains("public class AnotherChild {"); } - @Test - public void testAdditionalPropertiesFieldIsDeclaredOncePerHierarchyForGson() { - final Path output = generateOkHttpGsonWithAdditionalProperties("src/test/resources/3_0/allOf_extension_parent.yaml"); + @DataProvider + Object[][] librariesDeclaringTheGsonBagOncePerHierarchy() { + return new Object[][]{{Library.OKHTTP_GSON}, {Library.OKHTTP}}; + } + + @Test(dataProvider = "librariesDeclaringTheGsonBagOncePerHierarchy") + public void testAdditionalPropertiesFieldIsDeclaredOncePerHierarchyForGson(Library library) { + final Path output = generateWithAdditionalProperties(library, "src/test/resources/3_0/allOf_extension_parent.yaml"); // exactly one class per hierarchy declares the bag; descendants inherit it assertThat(output.resolve("src/main/java/xyz/abcdef/model/Person.java")) @@ -2357,9 +2435,9 @@ public void testAdditionalPropertiesFieldIsDeclaredOncePerHierarchyForGson() { .content().contains("private Map additionalProperties;"); } - @Test - public void testAdditionalPropertiesFieldIsDeclaredOnceAcrossMultiLevelAllOfForGson() { - final Path output = generateOkHttpGsonWithAdditionalProperties("src/test/resources/3_0/java/okhttp-gson-additional-properties-allof-chain.yaml"); + @Test(dataProvider = "librariesDeclaringTheGsonBagOncePerHierarchy") + public void testAdditionalPropertiesFieldIsDeclaredOnceAcrossMultiLevelAllOfForGson(Library library) { + final Path output = generateWithAdditionalProperties(library, "src/test/resources/3_0/java/okhttp-gson-additional-properties-allof-chain.yaml"); // exactly one class per hierarchy declares the bag, also across Root <- Middle <- Leaf assertThat(output.resolve("src/main/java/xyz/abcdef/model/Root.java")) @@ -2378,7 +2456,7 @@ public void testAdditionalPropertiesFieldIsDeclaredOnceAcrossMultiLevelAllOfForG @Test public void testAdditionalPropertiesFieldIsDeclaredBelowOneOfAndAnyOfParentsForGson() { - final Path output = generateOkHttpGsonWithAdditionalProperties("src/test/resources/3_0/java/okhttp-gson-additional-properties-composed-parent.yaml"); + final Path output = generateWithAdditionalProperties(Library.OKHTTP_GSON, "src/test/resources/3_0/java/okhttp-gson-additional-properties-composed-parent.yaml"); // a oneOf/anyOf wrapper has no bag to inherit, so its allOf children declare their own assertThat(output.resolve("src/main/java/xyz/abcdef/model/Pet.java")) @@ -2401,11 +2479,38 @@ public void testAdditionalPropertiesFieldIsDeclaredBelowOneOfAndAnyOfParentsForG .doesNotContain("Map additionalProperties;"); } - private Path generateOkHttpGsonWithAdditionalProperties(String inputSpec) { + @Test + public void testAdditionalPropertiesFieldIsInheritedFromOneOfAndAnyOfParentsForOkHttp() { + final Path output = generateWithAdditionalProperties(Library.OKHTTP, "src/test/resources/3_0/java/okhttp-gson-additional-properties-composed-parent.yaml"); + + // unlike okhttp-gson, the okhttp oneOf/anyOf wrapper declares the bag (it keeps the properties the + // matched schema did not consume), so it is the topmost holder and its allOf children inherit it + assertThat(output.resolve("src/main/java/xyz/abcdef/model/Pet.java")) + .content() + .contains("public class Pet extends AbstractOpenApiSchema") + .contains("private Map additionalProperties;"); + assertThat(output.resolve("src/main/java/xyz/abcdef/model/ExtendedPet.java")) + .content() + .contains("public class ExtendedPet extends Pet {") + .contains("public ExtendedPet putAdditionalProperty(String key, Object value) {") + .doesNotContain("Map additionalProperties;"); + assertThat(output.resolve("src/main/java/xyz/abcdef/model/ExtendedShape.java")) + .content() + .contains("public class ExtendedShape extends Shape {") + .contains("public ExtendedShape putAdditionalProperty(String key, Object value) {") + .doesNotContain("Map additionalProperties;"); + assertThat(output.resolve("src/main/java/xyz/abcdef/model/ExtendedPetLeaf.java")) + .content() + .contains("public class ExtendedPetLeaf extends ExtendedPet {") + .contains("public ExtendedPetLeaf putAdditionalProperty(String key, Object value) {") + .doesNotContain("Map additionalProperties;"); + } + + private Path generateWithAdditionalProperties(Library library, String inputSpec) { final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName(JAVA_GENERATOR) - // use default `okhttp-gson` + .setLibrary(library.value) .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model") .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") @@ -3261,6 +3366,46 @@ public void testRestTemplateHandleURIEnum() { testHandleURIEnum(JavaClientCodegen.RESTTEMPLATE, expectedInnerEnumLines, expectedEnumLines); } + @Test + public void testOkHttpBinaryResponseDetectionIndependentOfSerializer() { + // Jackson's TypeReference and JSON-B's GenericType resolve byte[] to the raw class (toString() "class [B"), + // so the binary-response check in ApiClient must not rely on Gson's TypeToken.toString() == "byte[]" alone. + for (String serializer : List.of("gson", "jackson", "jsonb")) { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName(JAVA_GENERATOR) + .setLibrary(JavaClientCodegen.OKHTTP) + .addAdditionalProperty(CodegenConstants.SERIALIZATION_LIBRARY, serializer) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + validateJavaSourceFiles(files); + + assertThat(output.resolve("src/main/java/org/openapitools/client/ApiClient.java")) + .content() + .contains("if (byte[].class.equals(returnType) || \"byte[]\".equals(returnType.toString())) {"); + } + } + + @Test + public void testOkHttpBuilderAdditionalPropertiesHelperDoesNotShadowSetters() { + // the builder's additional-properties helper must not share its name with a generated + // property setter, otherwise a declared property named `additionalProperties` of type + // Map on an additionalProperties:true schema produces an uncompilable Builder + final Map files = generateFromContract( + "src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml", + JavaClientCodegen.OKHTTP, + Map.of(AbstractJavaCodegen.GENERATE_BUILDERS, Boolean.TRUE, + CodegenConstants.SERIALIZATION_LIBRARY, "jackson", + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, Boolean.FALSE)); + + assertThat(files.get("AdditionalPropertiesClass.java").toPath()).content() + .contains("public AdditionalPropertiesClass.Builder putAdditionalProperties(Map additionalProperties) {") + .contains(".putAdditionalProperties(getAdditionalProperties())") + .doesNotContain("Builder additionalProperties(Map"); + } + @Test public void testOkHttpGsonHandleURIEnum() { String[] expectedInnerEnumLines = new String[]{ @@ -3302,6 +3447,7 @@ public void testMicroprofileHandleURIEnum() { public void testHandleURIEnumWithXml() { for (String library : List.of( JavaClientCodegen.OKHTTP_GSON, + JavaClientCodegen.OKHTTP, JavaClientCodegen.RESTTEMPLATE, JavaClientCodegen.NATIVE)) { final Path output = newTempFolder(); @@ -6036,6 +6182,277 @@ private static JavaClientCodegen newRetrofit2Codegen(Map propert return codegen; } + private static JavaClientCodegen newOkhttpCodegen(Map properties) { + JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setLibrary(JavaClientCodegen.OKHTTP); + codegen.additionalProperties().putAll(properties); + codegen.processOpts(); + return codegen; + } + + @Test(description = "the okhttp library drives Gson, Jackson and JSON-B from one template set, so it " + + "must expose the resolved serialization library as three mutually exclusive mustache flags") + public void testOkhttpDefaultsToGson() { + JavaClientCodegen codegen = newOkhttpCodegen(Map.of()); + + assertEquals(codegen.getSerializationLibrary(), SERIALIZATION_LIBRARY_GSON); + assertThat(codegen.additionalProperties()) + .contains(entry("isGson", true), entry("isJackson", false), entry("isJsonb", false)); + } + + @Test + public void testOkhttpWithJackson() { + JavaClientCodegen codegen = newOkhttpCodegen( + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JACKSON)); + + assertEquals(codegen.getSerializationLibrary(), SERIALIZATION_LIBRARY_JACKSON); + assertThat(codegen.additionalProperties()) + .contains(entry("isGson", false), entry("isJackson", true), entry("isJsonb", false)); + } + + @Test(description = "openApiNullable is jackson-databind-nullable, which the okhttp pom omits for " + + "JSON-B; leaving the flag on would emit JsonNullable references that cannot resolve") + public void testOkhttpWithJsonbForcesOpenApiNullableOff() { + JavaClientCodegen codegen = newOkhttpCodegen( + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JSONB, + JavaClientCodegen.OPENAPI_NULLABLE, true)); + + assertEquals(codegen.getSerializationLibrary(), SERIALIZATION_LIBRARY_JSONB); + assertThat(codegen.additionalProperties()) + .contains(entry("isGson", false), entry("isJackson", false), entry("isJsonb", true), + entry(JavaClientCodegen.OPENAPI_NULLABLE, false)); + } + + @Test + public void testOkhttpWithJackson3() { + JavaClientCodegen codegen = newOkhttpCodegen( + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JACKSON, + USE_JACKSON_3, true)); + + assertThat(codegen.additionalProperties()) + .contains(entry("isJackson", true), entry(USE_JACKSON_3, true), + entry("jacksonPackage", "tools.jackson")); + } + + @Test(description = "useJspecify must be accepted by the okhttp library") + public void testOkhttpWithJspecify() { + JavaClientCodegen codegen = newOkhttpCodegen(Map.of(USE_JSPECIFY, true)); + + assertThat(codegen.additionalProperties()).contains(entry(USE_JSPECIFY, true)); + } + + @Test(description = "okhttp's RetryingOAuth is self-contained, so it must not pull in " + + "OAuthOkHttpClient or the Apache Oltu dependency that okhttp-gson needs") + public void testOkhttpOAuthDoesNotUseOltu() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore.yaml", JavaClientCodegen.OKHTTP); + + assertThat(files).containsKey("RetryingOAuth.java"); + assertThat(files).doesNotContainKey("OAuthOkHttpClient.java"); + assertThat(files.get("RetryingOAuth.java")).content() + .contains("public static class TokenRequestBuilder") + .doesNotContain("org.apache.oltu"); + assertThat(files.get("pom.xml")).content() + .contains("okhttp-bom") + .doesNotContain("oltu"); + } + + @DataProvider(name = "okhttpSerializers") + public Object[][] okhttpSerializers() { + return new Object[][]{ + {SERIALIZATION_LIBRARY_GSON}, {SERIALIZATION_LIBRARY_JACKSON}, {SERIALIZATION_LIBRARY_JSONB} + }; + } + + @Test(dataProvider = "okhttpSerializers", + description = "every serialization library must produce a compilable client from the same templates") + public void testOkhttpGeneratesForEverySerializer(String serializationLibrary) { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore.yaml", JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, serializationLibrary)); + + assertThat(files).containsKeys("ApiClient.java", "JSON.java", "ApiCallback.java", "Pet.java"); + // JsonNullable and JsonIgnore are Jackson types; they must not leak into Gson or JSON-B output + if (!SERIALIZATION_LIBRARY_JACKSON.equals(serializationLibrary)) { + assertThat(files.get("Pet.java")).content().doesNotContain("JsonNullable"); + } + } + + @Test(description = "the okhttp templates never emit JsonNullable fields, so openApiNullable " + + "must be forced off for every serializer instead of emitting dead helpers") + public void testOkhttpForcesOpenApiNullableOff() { + JavaClientCodegen codegen = newOkhttpCodegen( + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JACKSON, + JavaClientCodegen.OPENAPI_NULLABLE, true)); + + assertThat(codegen.additionalProperties()).contains(entry(JavaClientCodegen.OPENAPI_NULLABLE, false)); + } + + @Test(description = "okhttp+Jackson3 must keep the lenient RFC3339 date handling the Jackson2 " + + "variant has, instead of silently falling back to stock jsr310 parsing") + public void testOkhttpJackson3GetsRfc3339Module() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore.yaml", JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JACKSON, + USE_JACKSON_3, true)); + + assertThat(files).containsKeys("RFC3339JavaTimeModule.java", "RFC3339InstantDeserializer.java"); + assertThat(files.get("JSON.java")).content().contains("new RFC3339JavaTimeModule()"); + } + + @Test(description = "JSON-B has no workable native polymorphism for discriminators that are " + + "also bean properties (Yasson rejects the key collision), so hierarchy roots need " + + "generated TypeSelector-style (de)serializers wired into the Jsonb config") + public void testOkhttpJsonbEmitsPolymorphismSerializers() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml", + JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JSONB)); + + assertThat(files.get("Animal.java")).content() + .contains("public static class CustomJsonbDeserializer implements JsonbDeserializer") + .contains("if (\"Cat\".equals(discriminatorValue)) {") + .doesNotContain("@JsonbTypeInfo"); + assertThat(files.get("JSON.java")).content() + .contains("plainJsonb = JsonbBuilder.create(config);") + .contains("config.withDeserializers(new org.openapitools.client.model.Animal.CustomJsonbDeserializer());"); + // subtypes must not run the discriminator dispatch, or root delegation would recurse + assertThat(files.get("Cat.java")).content().doesNotContain("discriminatorValue"); + } + + @Test(description = "a JSON-B parent without a discriminator (x-parent) gets the delegating root " + + "(de)serializers, since the leaf ones are skipped for every model with children") + public void testOkhttpJsonbParentWithoutDiscriminator() { + final Map files = generateFromContract( + "src/test/resources/3_0/allOf_extension_parent.yaml", + JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JSONB)); + + assertThat(files.get("Person.java")).content() + .contains("public static class CustomJsonbSerializer implements JsonbSerializer") + .contains("public static class CustomJsonbDeserializer implements JsonbDeserializer") + .contains("validateRequiredFields(jsonObj, openapiRequiredFields, \"Person\");") + .doesNotContain("discriminatorValue"); + assertThat(files.get("JSON.java")).content() + .contains("config.withSerializers(new org.openapitools.client.model.Person.CustomJsonbSerializer());") + .contains("config.withDeserializers(new org.openapitools.client.model.Person.CustomJsonbDeserializer());"); + } + + @Test(description = "okhttp Gson and JSON-B reject a string value excluded by `not: enum`, so a oneOf " + + "with a complementary branch resolves unambiguously (port of #25066)") + public void testOkhttpValidatesStringEnumExcludedByNot() { + Map files = generateFromContract( + "src/test/resources/3_1/java/oneof-not-enum.yaml", JavaClientCodegen.OKHTTP); + for (String model : List.of("Other.java", "OtherWithEnumRef.java")) { + assertThat(files.get(model)).content() + .contains("\"known\".equals(jsonElement.getAsJsonObject().get(\"kind\").getAsString())", + "matches a value disallowed by `not`"); + } + + // a child model enforces the `not` constraint of an inherited property too + files = generateFromContract("src/test/resources/3_1/java/not-enum-inherited.yaml", JavaClientCodegen.OKHTTP); + assertThat(files.get("Derived.java")).content() + .contains("public class Derived extends Base") + .contains("\"known\".equals(jsonElement.getAsJsonObject().get(\"kind\").getAsString())"); + files = generateFromContract("src/test/resources/3_1/java/not-enum-inherited.yaml", JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JSONB)); + assertThat(files.get("Derived.java")).content() + .contains("\"known\".equals(((jakarta.json.JsonString) jsonObj.get(\"kind\")).getString())"); + + files = generateFromContract("src/test/resources/3_1/java/oneof-not-enum.yaml", JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JSONB)); + for (String model : List.of("Other.java", "OtherWithEnumRef.java")) { + assertThat(files.get(model)).content() + .contains("\"known\".equals(((jakarta.json.JsonString) jsonObj.get(\"kind\")).getString())", + "matches a value disallowed by `not`"); + } + } + + @Test(description = "okhttp Jackson models import Arrays and Map only when the template uses them") + public void testOkhttpJacksonModelImportsArraysAndMapOnlyWhenUsed() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml", + JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JACKSON)); + + assertThat(files.get("Category.java")).content() + .doesNotContain("import java.util.Arrays;") + .doesNotContain("import java.util.Map;"); + // byte[] equals/hashCode + assertThat(files.get("FormatTest.java")).content().contains("import java.util.Arrays;"); + // openApiNullable is off for okhttp, so no JsonNullable hash helper is emitted and nothing here uses Arrays + assertThat(files.get("NullableClass.java")).content().doesNotContain("import java.util.Arrays;"); + } + + @Test(description = "composed oneOf models must keep okhttp-gson's fromJson/toJson helpers " + + "so migrating consumers do not lose API surface") + public void testOkhttpOneOfModelsKeepJsonHelpers() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml", + JavaClientCodegen.OKHTTP); + + assertThat(files.get("Fruit.java")).content() + .contains("public static Fruit fromJson(String jsonString) throws IOException {") + .contains("public String toJson() {"); + } + + @Test(description = "serializing a free-form additional property whose value is null must emit " + + "JSON null instead of crashing on JsonNull.getAsJsonObject()") + public void testOkhttpGsonAdditionalPropertiesNullSafe() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml", + JavaClientCodegen.OKHTTP); + + assertThat(files.get("NullableClass.java")).content() + .contains("if (jsonElement.isJsonNull()) {") + .contains("obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE);"); + // null is not an instance of anything: non-nullable oneOf must reject it + assertThat(files.get("JSON.java")).content() + .doesNotContain("if (instance == null) {\n return true;"); + } + + @Test(description = "JSON-B has no any-getter/any-setter, so additionalProperties=true models " + + "need generated custom (de)serializers wired into the Jsonb config to round-trip " + + "undeclared fields") + public void testOkhttpJsonbAdditionalPropertiesRoundTrip() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml", + JavaClientCodegen.OKHTTP, + Map.of(CodegenConstants.SERIALIZATION_LIBRARY, SERIALIZATION_LIBRARY_JSONB)); + + assertThat(files.get("NullableClass.java")).content() + .contains("public static class CustomJsonbSerializer implements JsonbSerializer") + .contains("public static class CustomJsonbDeserializer implements JsonbDeserializer"); + assertThat(files.get("JSON.java")).content() + .contains("config.withSerializers(new org.openapitools.client.model.NullableClass.CustomJsonbSerializer());") + .contains("config.withDeserializers(new org.openapitools.client.model.NullableClass.CustomJsonbDeserializer());"); + // a model without additionalProperties must not get the custom (de)serializers + assertThat(files.get("Pet.java")).content().doesNotContain("CustomJsonbSerializer"); + } + + @Test(description = "the setVerifyingSsl(false) insecure-TLS hook is generated unless opted out") + public void testOkhttpInsecureTlsHookGeneratedByDefault() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore.yaml", JavaClientCodegen.OKHTTP); + + assertThat(files.get("ApiClient.java")).content() + .contains("public ApiClient setVerifyingSsl(boolean verifyingSsl)") + .contains("checkClientTrusted"); + } + + @Test(description = "generateInsecureTlsHook=false must omit setVerifyingSsl and the trust-all " + + "TrustManager, e.g. for consumers whose static analysis flags that code") + public void testOkhttpInsecureTlsHookOmittedWhenDisabled() { + final Map files = generateFromContract( + "src/test/resources/3_0/petstore.yaml", JavaClientCodegen.OKHTTP, + Map.of(GENERATE_INSECURE_TLS_HOOK, false)); + + assertThat(files.get("ApiClient.java")).content() + .doesNotContain("verifyingSsl") + .doesNotContain("checkClientTrusted") + .doesNotContain("import java.security.cert.CertificateException;"); + } + @DataProvider(name = "jerseyLibraries") public static Object[][] jerseyLibraries() { return new Object[][]{{JavaClientCodegen.JERSEY2}, {JavaClientCodegen.JERSEY3}}; @@ -6146,12 +6563,17 @@ public void testRestTemplateGenerateClientAsBeanTrue() { .contains("import org.springframework.stereotype.Component;"); } - @Test - public void testOkHttpGsonParametersNamedLikeCallLocalsAreRenamed_issue25566() { + @DataProvider + Object[][] librariesSharingTheOkHttpCallTemplate() { + return new Object[][]{{Library.OKHTTP_GSON}, {Library.OKHTTP}}; + } + + @Test(dataProvider = "librariesSharingTheOkHttpCallTemplate") + public void testOkHttpGsonParametersNamedLikeCallLocalsAreRenamed_issue25566(Library library) { Path output = newTempFolder(); CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName(JAVA_GENERATOR) - .setLibrary(JavaClientCodegen.OKHTTP_GSON) + .setLibrary(library.value) .setInputSpec("src/test/resources/3_0/java/issue_25566.yaml") .setOutputDir(output.toString().replace("\\", "/")); @@ -6167,4 +6589,80 @@ public void testOkHttpGsonParametersNamedLikeCallLocalsAreRenamed_issue25566() { .contains("private String basePath;") .contains("public String getBasePath()"); } + + @DataProvider + Object[][] okHttpSerializers() { + return new Object[][]{{"gson", false}, {"jackson", false}, {"jackson", true}, {"jsonb", false}}; + } + + private Path generateOkHttpPetstore(String serializer, boolean jackson3) { + Path output = newTempFolder(); + CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName(JAVA_GENERATOR) + .setLibrary(JavaClientCodegen.OKHTTP) + .addAdditionalProperty(CodegenConstants.SERIALIZATION_LIBRARY, serializer) + .addAdditionalProperty(JavaClientCodegen.USE_JACKSON_3, jackson3) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + return output; + } + + /** + * A 2xx response whose body does not match the declared type used to surface differently per + * serializer (unchecked Gson/JSON-B/Jackson 3 exceptions, an ApiException with code 0 for + * Jackson 2). The okhttp ApiClient reports all of them as an ApiException that keeps the + * status and headers of the response. + */ + @Test(dataProvider = "okHttpSerializers") + public void testOkHttpReportsDeserializationFailuresAsApiException(String serializer, boolean jackson3) { + Path output = generateOkHttpPetstore(serializer, jackson3); + + assertThat(output.resolve("src/main/java/org/openapitools/client/ApiClient.java")).content() + .contains("} catch (IOException | RuntimeException e) {") + .contains("\"Failed to deserialize the response body as \" + returnType + \": \" + e.getMessage(),"); + } + + @Test(dataProvider = "okHttpSerializers") + public void testOkHttpModelsAndApisImportOnlyWhatTheyUse(String serializer, boolean jackson3) { + Path output = generateOkHttpPetstore(serializer, jackson3); + Path model = output.resolve("src/main/java/org/openapitools/client/model"); + + // Category has no enum, no container and no sibling reference + assertThat(model.resolve("Category.java")).content() + .doesNotContain("import com.google.gson.GsonBuilder;") + .doesNotContain("import com.google.gson.JsonArray;") + .doesNotContain("import com.google.gson.JsonNull;") + .doesNotContain("import com.google.gson.annotations.JsonAdapter;") + .doesNotContain("import com.fasterxml.jackson.annotation.JsonCreator;") + .doesNotContain("import com.fasterxml.jackson.annotation.JsonValue;") + .doesNotContain("import jakarta.json.bind.adapter.JsonbAdapter;") + .doesNotContain("import jakarta.json.bind.annotation.JsonbTypeAdapter;") + .doesNotContain("import java.util.List;"); + // Pet declares the status enum, so the enum annotations stay; its siblings need no import + assertThat(model.resolve("Pet.java")).content() + .doesNotContain("import org.openapitools.client.model.Category;") + .doesNotContain("import org.openapitools.client.model.Tag;") + .contains("import java.util.List;"); + if ("gson".equals(serializer)) { + assertThat(model.resolve("Pet.java")).content().contains("import com.google.gson.annotations.JsonAdapter;"); + } else if ("jackson".equals(serializer)) { + assertThat(model.resolve("Pet.java")).content() + .contains("import com.fasterxml.jackson.annotation.JsonCreator;") + .contains("import com.fasterxml.jackson.annotation.JsonValue;"); + assertThat(model.resolve("Category.java")).content().doesNotContain("import java.util.Arrays;"); + } else { + assertThat(model.resolve("Pet.java")).content() + .contains("import jakarta.json.bind.adapter.JsonbAdapter;") + .contains("import jakarta.json.bind.annotation.JsonbTypeAdapter;"); + assertThat(model.resolve("Category.java")).content().doesNotContain("import java.util.Map;"); + } + + assertThat(output.resolve("src/main/java/org/openapitools/client/api/PetApi.java")).content() + .doesNotContain("import org.openapitools.client.ProgressRequestBody;") + .doesNotContain("import org.openapitools.client.ProgressResponseBody;") + .doesNotContain("import java.io.IOException;"); + assertThat(output.resolve("src/main/java/org/openapitools/client/ApiCallback.java")).content() + .doesNotContain("import java.io.IOException;"); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaInnerEnumComparisonTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaInnerEnumComparisonTest.java index aad767d9b991..d4354df21789 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaInnerEnumComparisonTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaInnerEnumComparisonTest.java @@ -45,6 +45,7 @@ public Object[][] generators() { // Cover every affected inner-enum partial and both users of shared CXF/Micronaut partials. String[][] configurations = { {"java", "okhttp-gson"}, + {"java", "okhttp"}, {"java", "resttemplate"}, {"java", "microprofile"}, {"spring", null}, diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonLargeOneOfTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonLargeOneOfTest.java index ef47c08abe88..0e193e31ab6e 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonLargeOneOfTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonLargeOneOfTest.java @@ -31,11 +31,13 @@ public class JavaOkHttpGsonLargeOneOfTest { @DataProvider public Object[][] variantCounts() { - return new Object[][]{{2}, {100}, {101}, {260}}; + return new Object[][]{ + {2, "okhttp-gson"}, {100, "okhttp-gson"}, {101, "okhttp-gson"}, {260, "okhttp-gson"}, + {2, "okhttp"}, {100, "okhttp"}, {101, "okhttp"}, {260, "okhttp"}}; } @Test(dataProvider = "variantCounts") - public void testOneOfAdapterLoadsAndRoundTrips(int count) throws Exception { + public void testOneOfAdapterLoadsAndRoundTrips(int count, String library) throws Exception { Path output = newTempFolder(); Path spec = output.resolve("oneof.yaml"); StringBuilder yaml = new StringBuilder("openapi: 3.0.3\ninfo: {title: OneOf, version: '1'}\npaths: {}\ncomponents:\n schemas:\n Union:\n oneOf:\n"); @@ -46,7 +48,7 @@ public void testOneOfAdapterLoadsAndRoundTrips(int count) throws Exception { } for (int i = 0; i < count; i++) yaml.append(" Variant").append(i).append(":\n type: object\n properties:\n kind: {type: string}\n"); Files.writeString(spec, yaml.toString()); - CodegenConfigurator config = new CodegenConfigurator().setGeneratorName("java").setLibrary("okhttp-gson") + CodegenConfigurator config = new CodegenConfigurator().setGeneratorName("java").setLibrary(library) .setInputSpec(spec.toString()).setOutputDir(output.toString()) .addGlobalProperty("models", "").addGlobalProperty("modelDocs", "false") .addGlobalProperty("modelTests", "false"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonOneOfPrimitiveArrayTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonOneOfPrimitiveArrayTest.java index aef7d881c373..346f7e6d04a6 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonOneOfPrimitiveArrayTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonOneOfPrimitiveArrayTest.java @@ -13,6 +13,7 @@ import com.google.gson.TypeAdapterFactory; import org.openapitools.codegen.DefaultGenerator; import org.openapitools.codegen.config.CodegenConfigurator; +import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import javax.tools.ToolProvider; @@ -29,10 +30,15 @@ import static org.testng.Assert.*; public class JavaOkHttpGsonOneOfPrimitiveArrayTest { - @Test - public void testPrimitiveArrayRoundTrip() throws Exception { + @DataProvider + public Object[][] libraries() { + return new Object[][]{{"okhttp-gson"}, {"okhttp"}}; + } + + @Test(dataProvider = "libraries") + public void testPrimitiveArrayRoundTrip(String library) throws Exception { Path output = newTempFolder(); - CodegenConfigurator config = new CodegenConfigurator().setGeneratorName("java").setLibrary("okhttp-gson") + CodegenConfigurator config = new CodegenConfigurator().setGeneratorName("java").setLibrary(library) .setInputSpec("src/test/resources/3_0/java/oneof-primitive-array.yaml").setOutputDir(output.toString()) .addGlobalProperty("models", "").addGlobalProperty("modelDocs", "false") .addGlobalProperty("modelTests", "false"); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonUuidEnumTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonUuidEnumTest.java index 4ca42d4a4497..6490c07eda2c 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonUuidEnumTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaOkHttpGsonUuidEnumTest.java @@ -44,15 +44,16 @@ public class JavaOkHttpGsonUuidEnumTest { @DataProvider public Object[][] caseInsensitiveOptions() { - return new Object[][]{{false}, {true}}; + // the okhttp library shares the Gson inner-enum adapter shape and defaults to Gson serialization + return new Object[][]{{"okhttp-gson", false}, {"okhttp-gson", true}, {"okhttp", false}, {"okhttp", true}}; } @Test(dataProvider = "caseInsensitiveOptions") - public void testUuidEnumGsonRoundTrip(boolean caseInsensitive) throws Exception { + public void testUuidEnumGsonRoundTrip(String library, boolean caseInsensitive) throws Exception { Path output = newTempFolder(); CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") - .setLibrary("okhttp-gson") + .setLibrary(library) .setInputSpec("src/test/resources/3_0/issue_20952_inner_enum_comparison.yaml") .setOutputDir(output.toString()) .addGlobalProperty("models", "") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelTest.java index 32de36955ea6..ca25895e280b 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift6/Swift6ClientCodegenModelTest.java @@ -20,10 +20,12 @@ import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.media.*; import io.swagger.v3.parser.util.SchemaTypeUtil; +import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.CodegenProperty; import org.openapitools.codegen.DefaultCodegen; import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.config.GlobalSettings; import org.openapitools.codegen.languages.Swift6ClientCodegen; import org.openapitools.codegen.utils.ModelUtils; import org.testng.Assert; @@ -173,19 +175,33 @@ public void nestedMapRefTypeTest() { codegen.setOpenAPI(openAPI); codegen.processOpts(); - Map schemas = ModelUtils.getSchemas(openAPI); - Schema emailTemplateSchema = schemas.get("EmailTemplate"); - Assert.assertNotNull(emailTemplateSchema, "EmailTemplate schema should exist"); - - final CodegenModel cm = codegen.fromModel("EmailTemplate", emailTemplateSchema); - - CodegenProperty translationProp = cm.vars.stream() - .filter(p -> p.baseName.equals("translationOverridesByLocale")) - .findFirst().orElse(null); - Assert.assertNotNull(translationProp, "translationOverridesByLocale property should exist"); - // Must be [String: [String: String]], NOT [String: Dictionary] - Assert.assertEquals(translationProp.dataType, "[String: [String: String]]", - "Nested map via $ref should resolve to [String: [String: String]]"); + // This assertion depends on alias unwrapping, which ModelUtils.unaliasSchema() skips while the static + // GlobalSettings flag generateAliasAsModel is true. Other tests (e.g. CodegenConfiguratorTest) set that flag + // through DefaultCodegen.processOpts() and it survives across test classes in the same JVM, so pin it to + // false for this test only and restore whatever was there before. + final String previousGenerateAliasAsModel = GlobalSettings.getProperty(CodegenConstants.GENERATE_ALIAS_AS_MODEL); + ModelUtils.setGenerateAliasAsModel(false); + try { + Map schemas = ModelUtils.getSchemas(openAPI); + Schema emailTemplateSchema = schemas.get("EmailTemplate"); + Assert.assertNotNull(emailTemplateSchema, "EmailTemplate schema should exist"); + + final CodegenModel cm = codegen.fromModel("EmailTemplate", emailTemplateSchema); + + CodegenProperty translationProp = cm.vars.stream() + .filter(p -> p.baseName.equals("translationOverridesByLocale")) + .findFirst().orElse(null); + Assert.assertNotNull(translationProp, "translationOverridesByLocale property should exist"); + // Must be [String: [String: String]], NOT [String: Dictionary] + Assert.assertEquals(translationProp.dataType, "[String: [String: String]]", + "Nested map via $ref should resolve to [String: [String: String]]"); + } finally { + if (previousGenerateAliasAsModel == null) { + GlobalSettings.clearProperty(CodegenConstants.GENERATE_ALIAS_AS_MODEL); + } else { + GlobalSettings.setProperty(CodegenConstants.GENERATE_ALIAS_AS_MODEL, previousGenerateAliasAsModel); + } + } } } diff --git a/modules/openapi-generator/src/test/resources/3_1/java/not-enum-inherited.yaml b/modules/openapi-generator/src/test/resources/3_1/java/not-enum-inherited.yaml new file mode 100644 index 000000000000..d37cb43b2182 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/java/not-enum-inherited.yaml @@ -0,0 +1,27 @@ +openapi: 3.1.0 + +info: + title: not enum on an inherited property + version: 1.0.0 + +paths: {} + +components: + schemas: + Base: + type: object + x-parent: true + properties: + kind: + type: string + not: + enum: + - known + + Derived: + allOf: + - $ref: '#/components/schemas/Base' + - type: object + properties: + name: + type: string diff --git a/pom.xml b/pom.xml index ae4c69c7537d..5c5d56a27388 100644 --- a/pom.xml +++ b/pom.xml @@ -690,6 +690,46 @@ samples/client/petstore/java/okhttp-gson-parcelableModel + + java-client-okhttp + + + env + java + + + + samples/client/petstore/java/okhttp + samples/client/petstore/java/okhttp-jackson + samples/client/petstore/java/okhttp-jsonb + + + + + java-client-okhttp-jackson3 + + [17,) + + env + java + + + + samples/client/petstore/java/okhttp-jackson3 + + + + java-client-okhttp-parcelable + + + env + java + + + + samples/client/petstore/java/okhttp-parcelableModel + + java-client-retrofit2 diff --git a/samples/client/petstore/java/okhttp-group-parameter/.github/workflows/maven.yml b/samples/client/petstore/java/okhttp-group-parameter/.github/workflows/maven.yml new file mode 100644 index 000000000000..460f78bfd1b2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build OpenAPI Petstore + runs-on: ubuntu-latest + strategy: + matrix: + java: [ 17, 21 ] + steps: + - uses: actions/checkout@v4 + - name: Set up JDK + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml diff --git a/samples/client/petstore/java/okhttp-group-parameter/.gitignore b/samples/client/petstore/java/okhttp-group-parameter/.gitignore new file mode 100644 index 000000000000..a530464afa1b --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# 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 +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator-ignore b/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator/FILES new file mode 100644 index 000000000000..7f6af5610518 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator/FILES @@ -0,0 +1,51 @@ +.github/workflows/maven.yml +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/Category.md +docs/ModelApiResponse.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/Tag.md +docs/User.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiCallback.java +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/ApiException.java +src/main/java/org/openapitools/client/ApiResponse.java +src/main/java/org/openapitools/client/Configuration.java +src/main/java/org/openapitools/client/GzipRequestInterceptor.java +src/main/java/org/openapitools/client/JSON.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/ProgressRequestBody.java +src/main/java/org/openapitools/client/ProgressResponseBody.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/PetApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/auth/OAuth.java +src/main/java/org/openapitools/client/auth/OAuthFlow.java +src/main/java/org/openapitools/client/auth/RetryingOAuth.java +src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/ModelApiResponse.java +src/main/java/org/openapitools/client/model/Order.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/User.java diff --git a/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator/VERSION new file mode 100644 index 000000000000..84bf2ceeaede --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.28.0-SNAPSHOT diff --git a/samples/client/petstore/java/okhttp-group-parameter/.travis.yml b/samples/client/petstore/java/okhttp-group-parameter/.travis.yml new file mode 100644 index 000000000000..1b6741c083c7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/client/echo_api/java/okhttp-gson-user-defined-templates/README.md b/samples/client/petstore/java/okhttp-group-parameter/README.md similarity index 69% rename from samples/client/echo_api/java/okhttp-gson-user-defined-templates/README.md rename to samples/client/petstore/java/okhttp-group-parameter/README.md index 61555e362393..f027782c1153 100644 --- a/samples/client/echo_api/java/okhttp-gson-user-defined-templates/README.md +++ b/samples/client/petstore/java/okhttp-group-parameter/README.md @@ -1,8 +1,8 @@ -# openapi-java-client +# petstore-okhttp-group-parameter OpenAPI Petstore - API version: 1.0.0 - - Generator version: 7.6.0-SNAPSHOT + - Generator version: 7.28.0-SNAPSHOT This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. @@ -39,7 +39,7 @@ Add this dependency to your project's POM: ```xml org.openapitools - openapi-java-client + petstore-okhttp-group-parameter 1.0.0 compile @@ -51,12 +51,12 @@ Add this dependency to your project's build file: ```groovy repositories { - mavenCentral() // Needed if the 'openapi-java-client' jar has been published to maven central. - mavenLocal() // Needed if the 'openapi-java-client' jar has been published to the local maven repo. + mavenCentral() // Needed if the 'petstore-okhttp-group-parameter' jar has been published to maven central. + mavenLocal() // Needed if the 'petstore-okhttp-group-parameter' jar has been published to the local maven repo. } dependencies { - implementation "org.openapitools:openapi-java-client:1.0.0" + implementation "org.openapitools:petstore-okhttp-group-parameter:1.0.0" } ``` @@ -70,7 +70,7 @@ mvn clean package Then manually install the following JARs: -* `target/openapi-java-client-1.0.0.jar` +* `target/petstore-okhttp-group-parameter-1.0.0.jar` * `target/lib/*.jar` ## Getting Started @@ -84,7 +84,7 @@ import org.openapitools.client.ApiClient; import org.openapitools.client.ApiException; import org.openapitools.client.Configuration; import org.openapitools.client.auth.*; -import org.openapitools.client.models.*; +import org.openapitools.client.model.*; import org.openapitools.client.api.PetApi; public class Example { @@ -99,7 +99,8 @@ public class Example { PetApi apiInstance = new PetApi(defaultClient); Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store try { - Pet result = apiInstance.addPet(pet); + Pet result = apiInstance.addPet(pet) + .execute(); System.out.println(result); } catch (ApiException e) { System.err.println("Exception when calling PetApi#addPet"); @@ -127,18 +128,6 @@ Class | Method | HTTP request | Description *PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet *PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data *PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image -*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID -*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID -*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet -*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user -*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array -*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array -*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user -*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name -*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system -*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session -*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user ## Documentation for Models diff --git a/samples/client/petstore/java/okhttp-group-parameter/api/openapi.yaml b/samples/client/petstore/java/okhttp-group-parameter/api/openapi.yaml new file mode 100644 index 000000000000..80c98f47cea9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/api/openapi.yaml @@ -0,0 +1,519 @@ +openapi: 3.0.0 +info: + description: "This is a sample server Petstore server. For this sample, you can\ + \ use the api key `special-key` to test the authorization filters." + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: "#/components/requestBodies/Pet" + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/Pet" + application/json: + schema: + $ref: "#/components/schemas/Pet" + description: successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + x-content-type: application/json + x-accepts: + - application/json + - application/xml + put: + description: "" + operationId: updatePet + requestBody: + $ref: "#/components/requestBodies/Pet" + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/Pet" + application/json: + schema: + $ref: "#/components/schemas/Pet" + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + x-content-type: application/json + x-accepts: + - application/json + - application/xml + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - deprecated: true + description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: "#/components/schemas/Pet" + type: array + application/json: + schema: + items: + $ref: "#/components/schemas/Pet" + type: array + description: successful operation + "400": + description: Invalid status value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by status + tags: + - pet + x-accepts: + - application/json + - application/xml + /pet/findByTags: + get: + deprecated: true + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: "#/components/schemas/Pet" + type: array + application/json: + schema: + items: + $ref: "#/components/schemas/Pet" + type: array + description: successful operation + "400": + description: Invalid tag value + security: + - petstore_auth: + - read:pets + summary: Finds Pets by tags + tags: + - pet + x-accepts: + - application/json + - application/xml + /pet/{petId}: + delete: + description: "" + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + x-accepts: + - application/json + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/Pet" + application/json: + schema: + $ref: "#/components/schemas/Pet" + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + x-accepts: + - application/json + - application/xml + post: + description: "" + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/updatePetWithForm_request" + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + x-group-parameters: false + x-content-type: application/x-www-form-urlencoded + x-accepts: + - application/json + /pet/{petId}/uploadImage: + post: + description: "" + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/uploadFile_request" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + x-content-type: multipart/form-data + x-accepts: + - application/json +components: + requestBodies: + UserArray: + content: + application/json: + schema: + items: + $ref: "#/components/schemas/User" + type: array + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + application/xml: + schema: + $ref: "#/components/schemas/Pet" + description: Pet object that needs to be added to the store + required: true + schemas: + Order: + description: An order for a pets from the pet store + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + title: Pet Order + type: object + xml: + name: Order + Category: + description: A category for a pet + example: + id: 6 + name: name + properties: + id: + format: int64 + type: integer + name: + pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" + type: string + title: Pet category + type: object + xml: + name: Category + User: + description: A User who is purchasing from the pet store + properties: + id: + format: int64 + type: integer + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + title: a User + type: object + xml: + name: User + Tag: + description: A tag for a pet + example: + id: 1 + name: name + properties: + id: + format: int64 + type: integer + name: + type: string + title: Pet Tag + type: object + xml: + name: Tag + Pet: + description: A pet for sale in the pet store + example: + id: 0 + category: + id: 6 + name: name + name: doggie + photoUrls: + - photoUrls + - photoUrls + tags: + - id: 1 + name: name + - id: 1 + name: name + status: available + properties: + id: + format: int64 + type: integer + category: + $ref: "#/components/schemas/Category" + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: "#/components/schemas/Tag" + type: array + xml: + name: tag + wrapped: true + status: + deprecated: true + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + title: a Pet + type: object + xml: + name: Pet + ApiResponse: + description: Describes the result of uploading an image resource + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + title: An uploaded response + type: object + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey + diff --git a/samples/client/petstore/java/okhttp-group-parameter/build.gradle b/samples/client/petstore/java/okhttp-group-parameter/build.gradle new file mode 100644 index 000000000000..0611f80dd806 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/build.gradle @@ -0,0 +1,60 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' +apply plugin: 'java' +apply plugin: 'maven-publish' + +group = 'org.openapitools' +version = '1.0.0' + +repositories { + mavenCentral() +} +sourceSets { + main.java.srcDirs = ['src/main/java'] +} + + +sourceCompatibility = JavaVersion.VERSION_1_8 +targetCompatibility = JavaVersion.VERSION_1_8 + +publishing { + publications { + maven(MavenPublication) { + artifactId = 'petstore-okhttp-group-parameter' + from components.java + } + } +} + +task execute(type:JavaExec) { + mainClass = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} + +ext { + jakarta_annotation_version = "1.3.5" + okhttp_version = "5.4.0" +} + +dependencies { + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation "com.squareup.okhttp3:okhttp:$okhttp_version" + implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version" + implementation 'com.google.code.gson:gson:2.10.1' + implementation 'io.gsonfire:gson-fire:1.9.0' + compileOnly "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.3' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.3' +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} + +test { + useJUnitPlatform() + dependsOn 'cleanTest' + testLogging { + events "passed", "skipped", "failed" + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/build.sbt b/samples/client/petstore/java/okhttp-group-parameter/build.sbt new file mode 100644 index 000000000000..b17b582a5a73 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/build.sbt @@ -0,0 +1,24 @@ +// Keep the bytecode level in sync with the Maven and Gradle builds. +val javaVersion = "1.8" + +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "petstore-okhttp-group-parameter", + version := "1.0.0", + scalaVersion := "2.13.6", + scalacOptions ++= Seq("-feature"), + compile / javacOptions ++= Seq("-Xlint:deprecation", "-source", javaVersion, "-target", javaVersion), + Compile / packageDoc / publishArtifact := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.google.code.findbugs" % "jsr305" % "3.0.2", + "com.squareup.okhttp3" % "okhttp-jvm" % "5.4.0", + "com.squareup.okhttp3" % "logging-interceptor" % "5.4.0", + "com.google.code.gson" % "gson" % "2.10.1", + "io.gsonfire" % "gson-fire" % "1.9.0", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5", + "org.junit.jupiter" % "junit-jupiter-api" % "5.10.3" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/okhttp-group-parameter/docs/Category.md b/samples/client/petstore/java/okhttp-group-parameter/docs/Category.md new file mode 100644 index 000000000000..a7fc939d252e --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/docs/Category.md @@ -0,0 +1,15 @@ + + +# Category + +A category for a pet + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/docs/ModelApiResponse.md b/samples/client/petstore/java/okhttp-group-parameter/docs/ModelApiResponse.md new file mode 100644 index 000000000000..cd7e3c400be6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/docs/ModelApiResponse.md @@ -0,0 +1,16 @@ + + +# ModelApiResponse + +Describes the result of uploading an image resource + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**code** | **Integer** | | [optional] | +|**type** | **String** | | [optional] | +|**message** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/docs/Order.md b/samples/client/petstore/java/okhttp-group-parameter/docs/Order.md new file mode 100644 index 000000000000..0c33059b8b6a --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/docs/Order.md @@ -0,0 +1,29 @@ + + +# Order + +An order for a pets from the pet store + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**petId** | **Long** | | [optional] | +|**quantity** | **Integer** | | [optional] | +|**shipDate** | **OffsetDateTime** | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] | +|**complete** | **Boolean** | | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| PLACED | "placed" | +| APPROVED | "approved" | +| DELIVERED | "delivered" | + + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/docs/Pet.md b/samples/client/petstore/java/okhttp-group-parameter/docs/Pet.md new file mode 100644 index 000000000000..8bb363301232 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/docs/Pet.md @@ -0,0 +1,29 @@ + + +# Pet + +A pet for sale in the pet store + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/docs/PetApi.md b/samples/client/petstore/java/okhttp-group-parameter/docs/PetApi.md new file mode 100644 index 000000000000..a276eb4a2057 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/docs/PetApi.md @@ -0,0 +1,580 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store | +| [**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID | +| [**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet | +| [**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image | + + + +# **addPet** +> Pet addPet(pet).execute(); + +Add a new pet to the store + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.addPet(pet) + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + + +# **deletePet** +> deletePet(petId).apiKey(apiKey).execute(); + +Deletes a pet + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + apiInstance.deletePet(petId) + .apiKey(apiKey) + .execute(); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| Pet id to delete | | +| **apiKey** | **String**| | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status).execute(); + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status) + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags).execute(); + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List tags = Arrays.asList(); // List | Tags to filter by + try { + List result = apiInstance.findPetsByTags(tags) + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **tags** | [**List<String>**](String.md)| Tags to filter by | | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +# **getPetById** +> Pet getPetById(petId).execute(); + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId) + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +# **updatePet** +> Pet updatePet(pet).execute(); + +Update an existing pet + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.updatePet(pet) + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + apiInstance.updatePetWithForm(petId, name, status); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet that needs to be updated | | +| **name** | **String**| Updated name of the pet | [optional] | +| **status** | **String**| Updated status of the pet | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +# **uploadFile** +> ModelApiResponse uploadFile(petId).additionalMetadata(additionalMetadata)._file(_file).execute(); + +uploads an image + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File _file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId) + .additionalMetadata(additionalMetadata) + ._file(_file) + .execute(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | +| **_file** | **File**| file to upload | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java/okhttp-group-parameter/docs/Tag.md b/samples/client/petstore/java/okhttp-group-parameter/docs/Tag.md new file mode 100644 index 000000000000..abfde4afb501 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/docs/Tag.md @@ -0,0 +1,15 @@ + + +# Tag + +A tag for a pet + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/docs/User.md b/samples/client/petstore/java/okhttp-group-parameter/docs/User.md new file mode 100644 index 000000000000..426845227bd3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/docs/User.md @@ -0,0 +1,21 @@ + + +# User + +A User who is purchasing from the pet store + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**username** | **String** | | [optional] | +|**firstName** | **String** | | [optional] | +|**lastName** | **String** | | [optional] | +|**email** | **String** | | [optional] | +|**password** | **String** | | [optional] | +|**phone** | **String** | | [optional] | +|**userStatus** | **Integer** | User Status | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/git_push.sh b/samples/client/petstore/java/okhttp-group-parameter/git_push.sh new file mode 100644 index 000000000000..a35991cd51a1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/git_push.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ -z "${git_host}" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \${git_host} to ${git_host}" +fi + +if [ -z "${git_user_id}" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \${git_user_id} to ${git_user_id}" +fi + +if [ -z "${git_repo_id}" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \${git_repo_id} to ${git_repo_id}" +fi + +if [ -z "${release_note}" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \${release_note} to ${release_note}" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "${release_note}" + +# Sets the new remote +if [ -z "$(git remote)" ]; then # git remote not defined + if [ -z "${GIT_TOKEN:-}" ]; then + echo "[INFO] \${GIT_TOKEN} (environment variable) is not set. Using the git credential in your environment." + git remote add origin "https://${git_host}/${git_user_id}/${git_repo_id}.git" + else + git remote add origin "https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git" + fi +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/java/okhttp-group-parameter/gradle.properties b/samples/client/petstore/java/okhttp-group-parameter/gradle.properties new file mode 100644 index 000000000000..a3408578278a --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/gradle.properties @@ -0,0 +1,6 @@ +# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator). +# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option. +# +# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +# For example, uncomment below to build for Android +#target = android diff --git a/samples/client/petstore/java/okhttp-group-parameter/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/okhttp-group-parameter/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..e6441136f3d4 Binary files /dev/null and b/samples/client/petstore/java/okhttp-group-parameter/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/okhttp-group-parameter/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/okhttp-group-parameter/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..4f5eb9dcc0ef --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/java/okhttp-group-parameter/gradlew b/samples/client/petstore/java/okhttp-group-parameter/gradlew new file mode 100644 index 000000000000..9d0ce634cb11 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while +APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path +[ -h "$app_path" ] +do +ls=$( ls -ld "$app_path" ) +link=${ls#*' -> '} +case $link in #( +/*) app_path=$link ;; #( +*) app_path=$APP_HOME$link ;; +esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { +echo "$*" +} >&2 + +die () { +echo +echo "$*" +echo +exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( +CYGWIN* ) cygwin=true ;; #( +Darwin* ) darwin=true ;; #( +MSYS* | MINGW* ) msys=true ;; #( +NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then +if [ -x "$JAVA_HOME/jre/sh/java" ] ; then +# IBM's JDK on AIX uses strange locations for the executables +JAVACMD=$JAVA_HOME/jre/sh/java +else +JAVACMD=$JAVA_HOME/bin/java +fi +if [ ! -x "$JAVACMD" ] ; then +die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +else +JAVACMD=java +if ! command -v java >/dev/null 2>&1 +then +die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then +case $MAX_FD in #( +max*) +# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +MAX_FD=$( ulimit -H -n ) || +warn "Could not query maximum file descriptor limit" +esac +case $MAX_FD in #( +'' | soft) :;; #( +*) +# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +ulimit -n "$MAX_FD" || +warn "Could not set maximum file descriptor limit to $MAX_FD" +esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then +APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) +CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + +JAVACMD=$( cygpath --unix "$JAVACMD" ) + +# Now convert the arguments - kludge to limit ourselves to /bin/sh +for arg do +if +case $arg in #( +-*) false ;; # don't mess with options #( +/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath +[ -e "$t" ] ;; #( +*) false ;; +esac +then +arg=$( cygpath --path --ignore --mixed "$arg" ) +fi +# Roll the args list around exactly as many times as the number of +# args, so each arg winds up back in the position where it started, but +# possibly modified. +# +# NB: a `for` loop captures its iteration list before it begins, so +# changing the positional parameters here affects neither the number of +# iterations, nor the values presented in `arg`. +shift # remove old arg +set -- "$@" "$arg" # push replacement arg +done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ +"-Dorg.gradle.appname=$APP_BASE_NAME" \ +-classpath "$CLASSPATH" \ +org.gradle.wrapper.GradleWrapperMain \ +"$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then +die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( +printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | +xargs -n1 | +sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | +tr '\n' ' ' +)" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/java/okhttp-group-parameter/gradlew.bat b/samples/client/petstore/java/okhttp-group-parameter/gradlew.bat new file mode 100644 index 000000000000..25da30dbdeee --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp-group-parameter/pom.xml b/samples/client/petstore/java/okhttp-group-parameter/pom.xml new file mode 100644 index 000000000000..66a4704d99b6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/pom.xml @@ -0,0 +1,289 @@ + + 4.0.0 + org.openapitools + petstore-okhttp-group-parameter + jar + petstore-okhttp-group-parameter + 1.0.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + https://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.4.1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + + + + + maven-dependency-plugin + 3.6.1 + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.5.0 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.6.3 + + + attach-javadocs + + jar + + + + + none + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.0 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.2.1 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + com.squareup.okhttp3 + okhttp-bom + ${okhttp-version} + pom + import + + + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + com.squareup.okhttp3 + okhttp-jvm + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + test + + + org.junit.platform + junit-platform-runner + ${junit-platform-runner.version} + test + + + + 1.8 + ${java.version} + ${java.version} + 1.9.0 + 5.4.0 + 2.10.1 + 1.3.5 + 5.10.3 + 1.10.0 + UTF-8 + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/settings.gradle b/samples/client/petstore/java/okhttp-group-parameter/settings.gradle new file mode 100644 index 000000000000..f7159b474695 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "petstore-okhttp-group-parameter" \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/AndroidManifest.xml b/samples/client/petstore/java/okhttp-group-parameter/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..54fbcb3da1e8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiCallback.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiCallback.java new file mode 100644 index 000000000000..3a5ffe39fbaf --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiCallback.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 000000000000..2dbbd4f1095e --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,1794 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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 org.openapitools.client.auth.RetryingOAuth.TokenRequestBuilder; + +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.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 org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.ApiKeyAuth; +import org.openapitools.client.auth.OAuth; +import org.openapitools.client.auth.RetryingOAuth; +import org.openapitools.client.auth.OAuthFlow; + +/** + *

ApiClient class.

+ */ +public class ApiClient { + + protected String basePath = "http://petstore.swagger.io/v2"; + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "http://petstore.swagger.io/v2", + "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 String tlsServerName; + + 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("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "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("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID + * + * @param clientId client ID + */ + public ApiClient(String clientId) { + this(clientId, null, null); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID and additional parameters + * + * @param clientId client ID + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, Map parameters) { + this(clientId, null, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID, secret, and additional parameters + * + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, String clientSecret, Map parameters) { + this(null, clientId, clientSecret, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters + * + * @param basePath base path + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String basePath, String clientId, String clientSecret, Map parameters) { + init(); + if (basePath != null) { + this.basePath = basePath; + } + + String tokenUrl = ""; + if (!"".equals(tokenUrl) && !URI.create(tokenUrl).isAbsolute()) { + URI uri = URI.create(getBasePath()); + tokenUrl = uri.getScheme() + ":" + + (uri.getAuthority() != null ? "//" + uri.getAuthority() : "") + + tokenUrl; + if (!URI.create(tokenUrl).isAbsolute()) { + throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL"); + } + } + RetryingOAuth retryingOAuth = new RetryingOAuth(tokenUrl, clientId, OAuthFlow.IMPLICIT, clientSecret, parameters); + authentications.put( + "petstore_auth", + retryingOAuth + ); + initHttpClient(Collections.singletonList(retryingOAuth)); + // Setup authentications (key: authentication name, value: authentication). + authentications.put("api_key", new ApiKeyAuth("header", "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/1.0.0/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://petstore.swagger.io/v2) + * @return An instance of ApiClient + */ + 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 ApiClient + * @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; + } + + /** + * Get TLS server name for SNI (Server Name Indication). + * + * @return The TLS server name + */ + public String getTlsServerName() { + return tlsServerName; + } + + /** + * Set TLS server name for SNI (Server Name Indication). + * This is used to verify the server certificate against a specific hostname + * instead of the hostname in the URL. + * + * @param tlsServerName The TLS server name to use for certificate verification + * @return ApiClient + */ + public ApiClient setTlsServerName(String tlsServerName) { + this.tlsServerName = tlsServerName; + 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 org.openapitools.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 org.openapitools.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 org.openapitools.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 org.openapitools.client.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + + /** + *

Set LocalDateTimeFormat.

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

Set LenientOnJson.

+ * + * @param lenientOnJson a boolean + * @return a {@link org.openapitools.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) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + 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; + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * + * @return Token request builder + */ + public TokenRequestBuilder getTokenEndPoint() { + for (Authentication apiAuth : authentications.values()) { + if (apiAuth instanceof RetryingOAuth) { + RetryingOAuth retryingOAuth = (RetryingOAuth) apiAuth; + return retryingOAuth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * 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); + } + } + + /** + * Format the given parameter object as an ASCII-safe JSON string. + * + * @param param Parameter + * @return JSON representation of the parameter + */ + public String parameterToJsonString(Object param) { + if (param == null) { + return ""; + } + String json = this.json.serialize(param); + int firstUnsafe = -1; + for (int i = 0; i < json.length(); i++) { + if (json.charAt(i) >= 0x7f) { + firstUnsafe = i; + break; + } + } + if (firstUnsafe == -1) { + return json; + } + + StringBuilder escaped = new StringBuilder(json.length()); + escaped.append(json, 0, firstUnsafe); + for (int i = firstUnsafe; i < json.length(); i++) { + char c = json.charAt(i); + if (c >= 0x7f) { + escaped.append("\\u"); + escaped.append(Character.forDigit((c >> 12) & 0xf, 16)); + escaped.append(Character.forDigit((c >> 8) & 0xf, 16)); + escaped.append(Character.forDigit((c >> 4) & 0xf, 16)); + escaped.append(Character.forDigit(c & 0xf, 16)); + } else { + escaped.append(c); + } + } + + return escaped.toString(); + } + + /** + * 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; + } + + // escape all delimiters except commas, which are URI reserved characters + String separator = collectionFormatSeparator(collectionFormat); + String delimiter = ",".equals(separator) ? separator : escapeString(separator); + + 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); + } + + String delimiter = collectionFormatSeparator(collectionFormat); + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Returns the separator between the items of a collection serialized in the + * given collection format. + * + * @param collectionFormat The collection format of the parameter ("csv" when unrecognized). + * @return The separator string. + */ + protected String collectionFormatSeparator(String collectionFormat) { + if ("ssv".equals(collectionFormat)) { + return " "; + } else if ("tsv".equals(collectionFormat)) { + return "\t"; + } else if ("pipes".equals(collectionFormat)) { + return "|"; + } + // collectionFormat is assumed to be "csv" by default + return ","; + } + + /** + * 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 org.openapitools.client.ApiException If fail to deserialize response body, i.e. cannot read response body, + * the body does not match the return type, or the Content-Type of the response is not supported. + * The exception carries the status code and headers of the response. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if (byte[].class.equals(returnType) || "byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e.getMessage(), e, response.code(), response.headers().toMultimap()); + } + } 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)) { + if (returnType.equals(String.class)) { + String respBodyString = respBody.string(); + if (respBodyString.isEmpty()) { + return null; + } + // Use String-based deserialize for String return type with fallback + return json.deserialize(respBodyString, returnType); + } else { + // Use InputStream-based deserialize which supports responses > 2GB + 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 | RuntimeException e) { + // The body could not be read or does not match the expected type. Serializers report + // that differently, some with an unchecked exception and some with an IOException, + // so it is always surfaced as an ApiException + // that keeps the status and headers of the response it belongs to. The body itself + // was consumed as a stream and is not available any more. + throw new ApiException( + "Failed to deserialize the response body as " + returnType + ": " + e.getMessage(), + e, + response.code(), + response.headers().toMultimap()); + } + } + + /** + * 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 org.openapitools.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 org.openapitools.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); + try(ResponseBody body = response.body(); BufferedSink sink = Okio.buffer(Okio.sink(file))) { + sink.writeAll(body.source()); + } + 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 org.openapitools.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 org.openapitools.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()); + response.close(); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + response.close(); + 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 org.openapitools.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 org.openapitools.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 org.openapitools.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); + + byte[] localVarPayload = requestBodyToBytes(reqBody); + + // update parameters with authentication settings + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RuntimeException("Authentication undefined: " + authName); + } + URI currentUri = URI.create(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); + auth.applyToParams(updatedQueryParams, headerParams, cookieParams, localVarPayload, method, currentUri); + } + + 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( + java.util.Locale.ROOT, + "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(java.util.Locale.ROOT, "%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format(java.util.Locale.ROOT, "%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * 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 { + trustManagers = trustedTrustManagers(); + hostnameVerifier = trustedHostnameVerifier(); + } + + 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); + } + } + + /** + * Build the trust managers that verify server certificates against the JVM's + * trust store, or against sslCaCert when one is configured. + * + * @return The trust managers to initialize the client's SSLContext with + * @throws GeneralSecurityException if sslCaCert cannot be loaded into a key store + */ + protected TrustManager[] trustedTrustManagers() throws GeneralSecurityException { + 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); + } + return trustManagerFactory.getTrustManagers(); + } + + /** + * Build the hostname verifier for TLS connections, honoring tlsServerName when set. + * + * @return The hostname verifier to configure the http client with + */ + protected HostnameVerifier trustedHostnameVerifier() { + if (tlsServerName != null && !tlsServerName.isEmpty()) { + return new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + // Verify the certificate against tlsServerName instead of the actual hostname + return OkHostnameVerifier.INSTANCE.verify(tlsServerName, session); + } + }; + } + return OkHostnameVerifier.INSTANCE; + } + + 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 byte array. + * + * @param requestBody The HTTP request object + * @return The byte array representation of the HTTP request body + * @throws org.openapitools.client.ApiException If fail to serialize the request body object into a byte array + */ + protected byte[] requestBodyToBytes(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readByteArray(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return new byte[0]; + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiException.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 000000000000..2314bcb7d300 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,167 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; +import java.util.List; + + +/** + *

ApiException class.

+ */ +@SuppressWarnings("serial") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +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.

+ */ + public ApiException() {} + + /** + *

Constructor for ApiException.

+ * + * @param throwable a {@link java.lang.Throwable} object + */ + public ApiException(Throwable throwable) { + super(throwable); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + */ + public ApiException(String message) { + super(message); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, Map> responseHeaders, String responseBody) { + this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message a {@link java.lang.String} object + */ + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message the error message + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } + + /** + * Get the exception message including HTTP response data. + * + * @return The exception message + */ + public String getMessage() { + return String.format(java.util.Locale.ROOT, "Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", + super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders()); + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiResponse.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiResponse.java new file mode 100644 index 000000000000..e6e5e89d366a --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ApiResponse.java @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + */ +public class ApiResponse { + private final int statusCode; + private final Map> headers; + private final T data; + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response body + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + /** + *

Get the status code.

+ * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

Get the headers.

+ * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

Get the data.

+ * + * @return the data + */ + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/Configuration.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/Configuration.java new file mode 100644 index 000000000000..ed308a9eeeca --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/Configuration.java @@ -0,0 +1,63 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +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.28.0-SNAPSHOT") +public class Configuration { + public static final String VERSION = "1.0.0"; + + private static final AtomicReference defaultApiClient = new AtomicReference<>(); + private static volatile Supplier apiClientFactory = ApiClient::new; + + /** + * 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/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/GzipRequestInterceptor.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/GzipRequestInterceptor.java new file mode 100644 index 000000000000..1e38992e5640 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/GzipRequestInterceptor.java @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + + /** + * Number of bytes handed to the sink per write while replaying a buffered body. Replaying the + * whole body in a single write would collapse an upload into one progress event, so it is + * replayed one okio segment at a time instead. + */ + private static final long WRITE_CHUNK_SIZE = 8192L; + + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + RequestBody body = originalRequest.body(); + if (body == null || originalRequest.header("Content-Encoding") != null || body.contentLength() == 0) { + return chain.proceed(originalRequest); + } + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), compress(body)) + .build(); + return chain.proceed(compressedRequest); + } + + /** + * Compresses the request body while keeping upload progress reporting truthful. + * + *

Compressing drains the body up front (see {@link #forceContentLength}). Draining a + * {@link ProgressRequestBody} here would fire every upload callback, the terminal one included, + * before a single byte reached the socket, and would report the uncompressed sizes. So the body + * that the {@code ProgressRequestBody} wraps is compressed instead, and the compressed bytes are + * re-wrapped with the same callback: progress is then reported against the bytes that are + * actually transmitted, as they are transmitted. + */ + private RequestBody compress(final RequestBody body) throws IOException { + if (body instanceof ProgressRequestBody) { + ProgressRequestBody progressBody = (ProgressRequestBody) body; + return new ProgressRequestBody(forceContentLength(gzip(progressBody.getDelegate())), progressBody.getCallback()); + } + return forceContentLength(gzip(body)); + } + + /** + * The gzip body reports an unknown content length, which makes OkHttp fall back to + * "Transfer-Encoding: chunked". Servers that reject chunked request bodies then fail every + * compressed request, so buffer the compressed bytes and republish their known length. + * + *

Known limitation: the compressed body is held in memory until the request completes, so a + * very large upload can exhaust the heap. Publishing the compressed length requires compressing + * the whole body first, so the buffering is inherent to the behaviour above; clients that upload + * bodies too large to buffer should leave gzip request compression disabled. + */ + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + // clone() shares the buffered segments instead of copying them, so the body stays + // replayable (OkHttp may re-send it after a redirect or an auth challenge) without + // a second copy of the payload. Write it out in chunks so that an enclosing + // ProgressRequestBody sees the upload advance rather than one all-at-once event. + Buffer source = buffer.clone(); + while (!source.exhausted()) { + sink.write(source, Math.min(source.size(), WRITE_CHUNK_SIZE)); + } + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/JSON.java new file mode 100644 index 000000000000..9f8e10d8193c --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/JSON.java @@ -0,0 +1,515 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import org.openapitools.client.model.AbstractOpenApiSchema; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; + + +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; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Date; +import java.util.Set; +import java.util.Map; + +/* + * A JSON utility class + */ +public class JSON { + private static Gson gson; + private static boolean isLenientOnJson = false; + private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private static LocalDateTimeTypeAdapter localDateTimeTypeAdapter = new LocalDateTimeTypeAdapter(); + private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + + static { + ensureInitialized(); + } + + public JSON() { + ensureInitialized(); + } + + private static synchronized void ensureInitialized() { + if (gson != null) { + // the shared static Gson is already built; rebuilding would discard a + // customization installed through setGson() + return; + } + GsonFireBuilder fireBuilder = new GsonFireBuilder(); + GsonBuilder builder = fireBuilder.createGsonBuilder(); + builder.registerTypeAdapter(Date.class, dateTypeAdapter); + builder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); + builder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); + builder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); + builder.registerTypeAdapter(LocalDateTime.class, localDateTimeTypeAdapter); + builder.registerTypeAdapter(byte[].class, byteArrayAdapter); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Category.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelApiResponse.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Order.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Pet.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Tag.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.User.CustomTypeAdapterFactory()); + gson = builder.create(); + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + + /** + * Get the internal serialization object. + * + * @return serialization object + */ + public static Object getSerializer() { + return gson; + } + + /** + * Set the internal serialization object. + * + * @param serializer serialization object + */ + public static void setSerializer(Object serializer) { + JSON.gson = (Gson) serializer; + } + + public static Gson getGson() { + return gson; + } + + public static void setGson(Gson gson) { + JSON.gson = gson; + } + + public static void setLenientOnJson(boolean lenientOnJson) { + JSON.isLenientOnJson = lenientOnJson; + } + + public static void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } + + public static boolean isInstanceOf(Class type, Object instance, Set> visited) { + if (instance == null) { + // null never matches a concrete schema type; nullable composed schemas accept + // null in setActualInstance before consulting this method + return false; + } + if (type.isInstance(instance)) { + return true; + } + if (instance instanceof AbstractOpenApiSchema) { + AbstractOpenApiSchema schema = (AbstractOpenApiSchema) instance; + visited.add(schema.getClass()); + for (Class allowedType : schema.getSchemas().values()) { + if (visited.contains(allowedType)) { + continue; + } + if (isInstanceOf(type, schema.getActualInstance(), visited)) { + return true; + } + } + } + return false; + } + + + + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + } + + /** + * 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 T deserialize(InputStream inputStream, Type returnType) throws IOException { + try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { + if (isLenientOnJson) { + 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 + */ + public static class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public static class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public static class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDateTime type + */ + public static class LocalDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE_TIME); + } + + public LocalDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + return LocalDateTime.parse(date, formatter); + } catch (DateTimeParseException e) { + if (date.length() > 10 && date.charAt(10) == ' ') { + date = date.substring(0, 10) + 'T' + date.substring(11); + return LocalDateTime.parse(date, formatter); + } + throw e; + } + } + } + } + + public static void setLocalDateTimeFormat(DateTimeFormatter dateFormat) { + localDateTimeTypeAdapter.setFormat(dateFormat); + } + + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public static class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public static class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/Pair.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 000000000000..9e3832693b5e --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Pair { + private final String name; + private final String value; + + public Pair(String name, String value) { + this.name = isValidString(name) ? name : ""; + this.value = isValidString(value) ? value : ""; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private static boolean isValidString(String arg) { + return arg != null; + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ProgressRequestBody.java new file mode 100644 index 000000000000..3af7b7b5fbd9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ProgressRequestBody.java @@ -0,0 +1,130 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; +import java.util.Objects; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = Objects.requireNonNull(callback); + } + + /** + * The body this one wraps. Package-private so that {@link GzipRequestInterceptor} can compress + * that body directly: draining this wrapper to compress it would report the upload as finished + * before the request reached the network. + * + * @return the wrapped request body + */ + RequestBody getDelegate() { + return requestBody; + } + + /** + * The callback this body reports upload progress to. Package-private so that + * {@link GzipRequestInterceptor} can re-wrap the compressed body with the same callback. + * + * @return the progress callback + */ + ApiCallback getCallback() { + return callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public boolean isDuplex() { + return requestBody.isDuplex(); + } + + @Override + public boolean isOneShot() { + return requestBody.isOneShot(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (isDuplex()) { + // A duplex body may keep writing on another thread after writeTo() returns, so completion + // can only be reported once the delegate closes the sink, not when this method returns. + requestBody.writeTo(Okio.buffer(new CountingSink(sink, true))); + return; + } + CountingSink countingSink = new CountingSink(sink, false); + BufferedSink bufferedSink = Okio.buffer(countingSink); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + long bytesWritten = countingSink.bytesWritten; + long contentLength = contentLength(); + callback.onUploadProgress(bytesWritten, contentLength, true); + } + + private final class CountingSink extends ForwardingSink { + + private long bytesWritten = 0L; + private long contentLength = 0L; + private final boolean reportDoneOnClose; + + public CountingSink(Sink delegate, boolean reportDoneOnClose) { + super(delegate); + this.reportDoneOnClose = reportDoneOnClose; + } + + @Override + public void close() throws IOException { + super.close(); + if (reportDoneOnClose) { + callback.onUploadProgress(bytesWritten, contentLength == 0 ? contentLength() : contentLength, true); + } + } + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + // writeTo emits the single terminal callback once the body is fully written; reporting + // done here as well would fire it twice for a known-length body. + callback.onUploadProgress(bytesWritten, contentLength, false); + } + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ProgressResponseBody.java new file mode 100644 index 000000000000..79742aca1c73 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ProgressResponseBody.java @@ -0,0 +1,82 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + // Memoized: OkHttp calls source() again on close(), and a second ForwardingSource would + // reset the progress counter and re-wrap an already partially consumed stream. + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + boolean done = false; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + if (bytesRead == -1) { + // an exhausted source keeps answering -1 to every further read (a buffered + // reader probes it more than once), so completion is reported only once + if (!done) { + done = true; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), true); + } + return bytesRead; + } + totalBytesRead += bytesRead; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), false); + return bytesRead; + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 000000000000..42a9ee6369de --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,72 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ServerVariable.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 000000000000..0003e04bd790 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/StringUtil.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 000000000000..85ce0250bfa0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/api/PetApi.java new file mode 100644 index 000000000000..413a6ce16b19 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/api/PetApi.java @@ -0,0 +1,1440 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + private okhttp3.Call addPetCall(@javax.annotation.Nonnull Pet pet, 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 = pet; + + // create path and map variables + String localVarPath = "/pet"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json", + "application/xml" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call addPetValidateBeforeCall(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'pet' is set + if (pet == null) { + throw new ApiException("Missing the required parameter 'pet' when calling addPet(Async)"); + } + + return addPetCall(pet, _callback); + + } + + + private ApiResponse addPetWithHttpInfo(@javax.annotation.Nonnull Pet pet) throws ApiException { + okhttp3.Call localVarCall = addPetValidateBeforeCall(pet, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + private okhttp3.Call addPetAsync(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = addPetValidateBeforeCall(pet, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIaddPetRequest { + @javax.annotation.Nonnull + private final Pet pet; + + private APIaddPetRequest(@javax.annotation.Nonnull Pet pet) { + this.pet = pet; + } + + /** + * Build call for addPet + * @param _callback ApiCallback API callback + * @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 successful operation -
405 Invalid input -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return addPetCall(pet, _callback); + } + + /** + * Execute addPet request + * @return Pet + * @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 successful operation -
405 Invalid input -
+ */ + public Pet execute() throws ApiException { + ApiResponse localVarResp = addPetWithHttpInfo(pet); + return localVarResp.getData(); + } + + /** + * Execute addPet request with HTTP info returned + * @return ApiResponse<Pet> + * @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 successful operation -
405 Invalid input -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return addPetWithHttpInfo(pet); + } + + /** + * Execute addPet request (asynchronously) + * @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 successful operation -
405 Invalid input -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return addPetAsync(pet, _callback); + } + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store (required) + * @return APIaddPetRequest + * @http.response.details + + + + + +
Response Details
Status Code Description Response Headers
200 successful operation -
405 Invalid input -
+ */ + public APIaddPetRequest addPet(@javax.annotation.Nonnull Pet pet) { + return new APIaddPetRequest(pet); + } + private okhttp3.Call deletePetCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey, 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 = "/pet/{petId}" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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); + } + + if (apiKey != null) { + localVarHeaderParams.put("api_key", localVarApiClient.parameterToString(apiKey)); + } + + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call deletePetValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + return deletePetCall(petId, apiKey, _callback); + + } + + + private ApiResponse deletePetWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey) throws ApiException { + okhttp3.Call localVarCall = deletePetValidateBeforeCall(petId, apiKey, null); + return localVarApiClient.execute(localVarCall); + } + + private okhttp3.Call deletePetAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = deletePetValidateBeforeCall(petId, apiKey, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + + public class APIdeletePetRequest { + @javax.annotation.Nonnull + private final Long petId; + @javax.annotation.Nullable + private String apiKey; + + private APIdeletePetRequest(@javax.annotation.Nonnull Long petId) { + this.petId = petId; + } + + /** + * Set apiKey + * @param apiKey (optional) + * @return APIdeletePetRequest + */ + public APIdeletePetRequest apiKey(@javax.annotation.Nullable String apiKey) { + this.apiKey = apiKey; + return this; + } + + /** + * Build call for deletePet + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
400 Invalid pet value -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return deletePetCall(petId, apiKey, _callback); + } + + /** + * Execute deletePet request + * @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
400 Invalid pet value -
+ */ + public void execute() throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Execute deletePet request with HTTP info returned + * @return ApiResponse<Void> + * @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
400 Invalid pet value -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Execute deletePet request (asynchronously) + * @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
400 Invalid pet value -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return deletePetAsync(petId, apiKey, _callback); + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @return APIdeletePetRequest + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
400 Invalid pet value -
+ */ + public APIdeletePetRequest deletePet(@javax.annotation.Nonnull Long petId) { + return new APIdeletePetRequest(petId); + } + private okhttp3.Call findPetsByStatusCall(@javax.annotation.Nonnull List status, 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 = "/pet/findByStatus"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (status != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "status", status)); + } + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call findPetsByStatusValidateBeforeCall(@javax.annotation.Nonnull List status, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + return findPetsByStatusCall(status, _callback); + + } + + + private ApiResponse> findPetsByStatusWithHttpInfo(@javax.annotation.Nonnull List status) throws ApiException { + okhttp3.Call localVarCall = findPetsByStatusValidateBeforeCall(status, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + private okhttp3.Call findPetsByStatusAsync(@javax.annotation.Nonnull List status, final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = findPetsByStatusValidateBeforeCall(status, _callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIfindPetsByStatusRequest { + @javax.annotation.Nonnull + private final List status; + + private APIfindPetsByStatusRequest(@javax.annotation.Nonnull List status) { + this.status = status; + } + + /** + * Build call for findPetsByStatus + * @param _callback ApiCallback API callback + * @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 successful operation -
400 Invalid status value -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return findPetsByStatusCall(status, _callback); + } + + /** + * Execute findPetsByStatus request + * @return List<Pet> + * @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 successful operation -
400 Invalid status value -
+ */ + public List execute() throws ApiException { + ApiResponse> localVarResp = findPetsByStatusWithHttpInfo(status); + return localVarResp.getData(); + } + + /** + * Execute findPetsByStatus request with HTTP info returned + * @return ApiResponse<List<Pet>> + * @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 successful operation -
400 Invalid status value -
+ */ + public ApiResponse> executeWithHttpInfo() throws ApiException { + return findPetsByStatusWithHttpInfo(status); + } + + /** + * Execute findPetsByStatus request (asynchronously) + * @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 successful operation -
400 Invalid status value -
+ */ + public okhttp3.Call executeAsync(final ApiCallback> _callback) throws ApiException { + return findPetsByStatusAsync(status, _callback); + } + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return APIfindPetsByStatusRequest + * @http.response.details + + + + + +
Response Details
Status Code Description Response Headers
200 successful operation -
400 Invalid status value -
+ */ + public APIfindPetsByStatusRequest findPetsByStatus(@javax.annotation.Nonnull List status) { + return new APIfindPetsByStatusRequest(status); + } + private okhttp3.Call findPetsByTagsCall(@javax.annotation.Nonnull List tags, 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 = "/pet/findByTags"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (tags != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "tags", tags)); + } + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @Deprecated + @SuppressWarnings("rawtypes") + private okhttp3.Call findPetsByTagsValidateBeforeCall(@javax.annotation.Nonnull List tags, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + return findPetsByTagsCall(tags, _callback); + + } + + + private ApiResponse> findPetsByTagsWithHttpInfo(@javax.annotation.Nonnull List tags) throws ApiException { + okhttp3.Call localVarCall = findPetsByTagsValidateBeforeCall(tags, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + private okhttp3.Call findPetsByTagsAsync(@javax.annotation.Nonnull List tags, final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = findPetsByTagsValidateBeforeCall(tags, _callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIfindPetsByTagsRequest { + @javax.annotation.Nonnull + private final List tags; + + private APIfindPetsByTagsRequest(@javax.annotation.Nonnull List tags) { + this.tags = tags; + } + + /** + * Build call for findPetsByTags + * @param _callback ApiCallback API callback + * @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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return findPetsByTagsCall(tags, _callback); + } + + /** + * Execute findPetsByTags request + * @return List<Pet> + * @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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public List execute() throws ApiException { + ApiResponse> localVarResp = findPetsByTagsWithHttpInfo(tags); + return localVarResp.getData(); + } + + /** + * Execute findPetsByTags request with HTTP info returned + * @return ApiResponse<List<Pet>> + * @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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public ApiResponse> executeWithHttpInfo() throws ApiException { + return findPetsByTagsWithHttpInfo(tags); + } + + /** + * Execute findPetsByTags request (asynchronously) + * @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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public okhttp3.Call executeAsync(final ApiCallback> _callback) throws ApiException { + return findPetsByTagsAsync(tags, _callback); + } + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return APIfindPetsByTagsRequest + * @http.response.details + + + + + +
Response Details
Status Code Description Response Headers
200 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public APIfindPetsByTagsRequest findPetsByTags(@javax.annotation.Nonnull List tags) { + return new APIfindPetsByTagsRequest(tags); + } + private okhttp3.Call getPetByIdCall(@javax.annotation.Nonnull Long petId, 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 = "/pet/{petId}" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { "api_key" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getPetByIdValidateBeforeCall(@javax.annotation.Nonnull Long petId, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + return getPetByIdCall(petId, _callback); + + } + + + private ApiResponse getPetByIdWithHttpInfo(@javax.annotation.Nonnull Long petId) throws ApiException { + okhttp3.Call localVarCall = getPetByIdValidateBeforeCall(petId, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + private okhttp3.Call getPetByIdAsync(@javax.annotation.Nonnull Long petId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getPetByIdValidateBeforeCall(petId, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIgetPetByIdRequest { + @javax.annotation.Nonnull + private final Long petId; + + private APIgetPetByIdRequest(@javax.annotation.Nonnull Long petId) { + this.petId = petId; + } + + /** + * Build call for getPetById + * @param _callback ApiCallback API callback + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return getPetByIdCall(petId, _callback); + } + + /** + * Execute getPetById request + * @return Pet + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public Pet execute() throws ApiException { + ApiResponse localVarResp = getPetByIdWithHttpInfo(petId); + return localVarResp.getData(); + } + + /** + * Execute getPetById request with HTTP info returned + * @return ApiResponse<Pet> + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return getPetByIdWithHttpInfo(petId); + } + + /** + * Execute getPetById request (asynchronously) + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return getPetByIdAsync(petId, _callback); + } + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return APIgetPetByIdRequest + * @http.response.details + + + + + + +
Response Details
Status Code Description Response Headers
200 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public APIgetPetByIdRequest getPetById(@javax.annotation.Nonnull Long petId) { + return new APIgetPetByIdRequest(petId); + } + private okhttp3.Call updatePetCall(@javax.annotation.Nonnull Pet pet, 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 = pet; + + // create path and map variables + String localVarPath = "/pet"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json", + "application/xml" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updatePetValidateBeforeCall(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'pet' is set + if (pet == null) { + throw new ApiException("Missing the required parameter 'pet' when calling updatePet(Async)"); + } + + return updatePetCall(pet, _callback); + + } + + + private ApiResponse updatePetWithHttpInfo(@javax.annotation.Nonnull Pet pet) throws ApiException { + okhttp3.Call localVarCall = updatePetValidateBeforeCall(pet, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + private okhttp3.Call updatePetAsync(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updatePetValidateBeforeCall(pet, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIupdatePetRequest { + @javax.annotation.Nonnull + private final Pet pet; + + private APIupdatePetRequest(@javax.annotation.Nonnull Pet pet) { + this.pet = pet; + } + + /** + * Build call for updatePet + * @param _callback ApiCallback API callback + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return updatePetCall(pet, _callback); + } + + /** + * Execute updatePet request + * @return Pet + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public Pet execute() throws ApiException { + ApiResponse localVarResp = updatePetWithHttpInfo(pet); + return localVarResp.getData(); + } + + /** + * Execute updatePet request with HTTP info returned + * @return ApiResponse<Pet> + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return updatePetWithHttpInfo(pet); + } + + /** + * Execute updatePet request (asynchronously) + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return updatePetAsync(pet, _callback); + } + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store (required) + * @return APIupdatePetRequest + * @http.response.details + + + + + + + +
Response Details
Status Code Description Response Headers
200 successful operation -
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public APIupdatePetRequest updatePet(@javax.annotation.Nonnull Pet pet) { + return new APIupdatePetRequest(pet); + } + /** + * Build call for updatePetWithForm + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (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
405 Invalid input -
+ */ + public okhttp3.Call updatePetWithFormCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status, 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 = "/pet/{petId}" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (name != null) { + localVarFormParams.put("name", name); + } + + if (status != null) { + localVarFormParams.put("status", status); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updatePetWithFormValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + return updatePetWithFormCall(petId, name, status, _callback); + + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @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
405 Invalid input -
+ */ + public void updatePetWithForm(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @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
405 Invalid input -
+ */ + public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status) throws ApiException { + okhttp3.Call localVarCall = updatePetWithFormValidateBeforeCall(petId, name, status, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (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
405 Invalid input -
+ */ + public okhttp3.Call updatePetWithFormAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updatePetWithFormValidateBeforeCall(petId, name, status, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + private okhttp3.Call uploadFileCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, 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 = "/pet/{petId}/uploadImage" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (additionalMetadata != null) { + localVarFormParams.put("additionalMetadata", additionalMetadata); + } + + if (_file != null) { + localVarFormParams.put("file", _file); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call uploadFileValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + return uploadFileCall(petId, additionalMetadata, _file, _callback); + + } + + + private ApiResponse uploadFileWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file) throws ApiException { + okhttp3.Call localVarCall = uploadFileValidateBeforeCall(petId, additionalMetadata, _file, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + private okhttp3.Call uploadFileAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = uploadFileValidateBeforeCall(petId, additionalMetadata, _file, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + + public class APIuploadFileRequest { + @javax.annotation.Nonnull + private final Long petId; + @javax.annotation.Nullable + private String additionalMetadata; + @javax.annotation.Nullable + private File _file; + + private APIuploadFileRequest(@javax.annotation.Nonnull Long petId) { + this.petId = petId; + } + + /** + * Set additionalMetadata + * @param additionalMetadata Additional data to pass to server (optional) + * @return APIuploadFileRequest + */ + public APIuploadFileRequest additionalMetadata(@javax.annotation.Nullable String additionalMetadata) { + this.additionalMetadata = additionalMetadata; + return this; + } + + /** + * Set _file + * @param _file file to upload (optional) + * @return APIuploadFileRequest + */ + public APIuploadFileRequest _file(@javax.annotation.Nullable File _file) { + this._file = _file; + return this; + } + + /** + * Build call for uploadFile + * @param _callback ApiCallback API callback + * @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 successful operation -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return uploadFileCall(petId, additionalMetadata, _file, _callback); + } + + /** + * Execute uploadFile request + * @return ModelApiResponse + * @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 successful operation -
+ */ + public ModelApiResponse execute() throws ApiException { + ApiResponse localVarResp = uploadFileWithHttpInfo(petId, additionalMetadata, _file); + return localVarResp.getData(); + } + + /** + * Execute uploadFile request with HTTP info returned + * @return ApiResponse<ModelApiResponse> + * @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 successful operation -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return uploadFileWithHttpInfo(petId, additionalMetadata, _file); + } + + /** + * Execute uploadFile request (asynchronously) + * @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 successful operation -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return uploadFileAsync(petId, additionalMetadata, _file, _callback); + } + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @return APIuploadFileRequest + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
200 successful operation -
+ */ + public APIuploadFileRequest uploadFile(@javax.annotation.Nonnull Long petId) { + return new APIuploadFileRequest(petId); + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..d14031cc76f7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 000000000000..0d93cfd01eee --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @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 ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, byte[] payload, String method, URI uri) throws ApiException; +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..a6e4cf65eae8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + // UTF-8 explicitly: Credentials.basic defaults to ISO-8859-1, which turns every character + // outside Latin-1 into '?'. This matches the shared Java HttpBasicAuth template. It differs on + // purpose from okhttp-gson and retrofit2, which keep the ISO-8859-1 default, so for such + // credentials this library sends a different Authorization header than okhttp-gson does. + headerParams.put("Authorization", Credentials.basic(username == null ? "" : username, password == null ? "" : password, StandardCharsets.UTF_8)); + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 000000000000..c9b5bf5d44a9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier == null ? null : tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token + */ + public void setBearerToken(String 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 + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/OAuth.java new file mode 100644 index 000000000000..d423cc4205b8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/OAuth.java @@ -0,0 +1,43 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (accessToken == null) { + return; + } + headerParams.put("Authorization", "Bearer " + accessToken); + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/OAuthFlow.java new file mode 100644 index 000000000000..492344a33afe --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/OAuthFlow.java @@ -0,0 +1,25 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +/** + * OAuth flows that are supported by this client + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public enum OAuthFlow { + ACCESS_CODE, //called authorizationCode in OpenAPI 3.0 + IMPLICIT, + PASSWORD, + APPLICATION //called clientCredentials in OpenAPI 3.0 +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/RetryingOAuth.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/RetryingOAuth.java new file mode 100644 index 000000000000..40d313b4c78f --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/auth/RetryingOAuth.java @@ -0,0 +1,245 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.JSON; +import org.openapitools.client.Pair; + +import okhttp3.FormBody; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RetryingOAuth extends OAuth implements Interceptor { + private final OkHttpClient client; + private final TokenRequestBuilder tokenRequestBuilder; + private final JSON json; + + public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) { + this.client = client; + this.tokenRequestBuilder = tokenRequestBuilder; + this.json = new JSON(); + } + + public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) { + this(new OkHttpClient(), tokenRequestBuilder); + } + + public RetryingOAuth( + String tokenUrl, + String clientId, + OAuthFlow flow, + String clientSecret, + Map parameters + ) { + this(TokenRequestBuilder.tokenLocation(tokenUrl) + .setClientId(clientId) + .setClientSecret(clientSecret)); + setFlow(flow); + if (parameters != null) { + for (Map.Entry entry : parameters.entrySet()) { + tokenRequestBuilder.setParameter(entry.getKey(), entry.getValue()); + } + } + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case ACCESS_CODE: + tokenRequestBuilder.setGrantType("authorization_code"); + break; + case IMPLICIT: + tokenRequestBuilder.setGrantType("implicit"); + break; + case PASSWORD: + tokenRequestBuilder.setGrantType("password"); + break; + case APPLICATION: + tokenRequestBuilder.setGrantType("client_credentials"); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) throws IOException { + return retryingIntercept(chain, true); + } + + private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException { + Request request = chain.request(); + + // If the request already has an authorization (e.g. Basic auth), proceed with the request as is + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // Get the token if it has not yet been acquired + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Remember the token this request is sent with: a 401/403 must only trigger a token refresh + // if no other thread has refreshed the token in the meantime (see updateAccessToken). + String requestAccessToken = getAccessToken(); + if (requestAccessToken != null) { + // Build the request + Request.Builder requestBuilder = request.newBuilder(); + requestBuilder.header("Authorization", "Bearer " + requestAccessToken); + + // Execute the request + Response response = chain.proceed(requestBuilder.build()); + + // 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row + if ( + response != null && + ( response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || + response.code() == HttpURLConnection.HTTP_FORBIDDEN ) && + updateTokenAndRetryOnAuthorizationFailure + ) { + try { + if (updateAccessToken(requestAccessToken)) { + if (response.body() != null) { + response.body().close(); + } + return retryingIntercept(chain, false); + } + } catch (Exception e) { + if (response.body() != null) { + response.body().close(); + } + throw e; + } + } + return response; + } + else { + return chain.proceed(chain.request()); + } + } + + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + Request tokenRequest = tokenRequestBuilder.build(); + try (Response response = client.newCall(tokenRequest).execute()) { + String body = response.body().string(); + if (!response.isSuccessful()) { + // surface the token endpoint's answer instead of silently sending the request unauthenticated + throw new IOException("OAuth token request to " + tokenRequest.url() + " failed with HTTP " + + response.code() + (body.isEmpty() ? "" : ": " + body)); + } + AccessTokenResponse tokenResponse; + try { + tokenResponse = json.deserialize(body, AccessTokenResponse.class); + } catch (RuntimeException e) { + throw new IOException("OAuth token response from " + tokenRequest.url() + " could not be parsed: " + body, e); + } + if (tokenResponse == null || tokenResponse.accessToken == null) { + throw new IOException("OAuth token response from " + tokenRequest.url() + " contains no access_token: " + body); + } + setAccessToken(tokenResponse.accessToken); + } + } + return getAccessToken() == null || !getAccessToken().equals(requestAccessToken); + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + // No implementation necessary + } + + public static class AccessTokenResponse { + @com.google.gson.annotations.SerializedName("access_token") + public String accessToken; + + @com.google.gson.annotations.SerializedName("token_type") + public String tokenType; + + @com.google.gson.annotations.SerializedName("expires_in") + public Long expiresIn; + + @com.google.gson.annotations.SerializedName("refresh_token") + public String refreshToken; + + @com.google.gson.annotations.SerializedName("scope") + public String scope; + } + + public static class TokenRequestBuilder { + private String tokenUrl; + private String clientId; + private String clientSecret; + private String grantType; + private final Map parameters = new HashMap<>(); + + public static TokenRequestBuilder tokenLocation(String tokenUrl) { + return new TokenRequestBuilder().setTokenUrl(tokenUrl); + } + + public TokenRequestBuilder setTokenUrl(String tokenUrl) { + this.tokenUrl = tokenUrl; + return this; + } + + public TokenRequestBuilder setClientId(String clientId) { + this.clientId = clientId; + return this; + } + + public TokenRequestBuilder setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + return this; + } + + public TokenRequestBuilder setGrantType(String grantType) { + this.grantType = grantType; + return this; + } + + public TokenRequestBuilder setParameter(String name, String value) { + this.parameters.put(name, value); + return this; + } + + public Request build() { + FormBody.Builder formBuilder = new FormBody.Builder(); + if (grantType != null) formBuilder.add("grant_type", grantType); + if (clientId != null) formBuilder.add("client_id", clientId); + if (clientSecret != null) formBuilder.add("client_secret", clientSecret); + for (Map.Entry entry : parameters.entrySet()) { + formBuilder.add(entry.getKey(), entry.getValue()); + } + + return new Request.Builder() + .url(tokenUrl) + .post(formBuilder.build()) + .build(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 000000000000..022e57d853b8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,139 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Map; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map> getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).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) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 000000000000..1d4a20cd7f99 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,303 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * A category for a pet + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Category { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nullable + private String name; + + public Category() { + } + + public Category id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Category name(@javax.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nullable + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nullable String name) { + this.name = name; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Category instance itself + */ + public Category putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name)&& + Objects.equals(this.additionalProperties, category.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name")); + + // 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 Category + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Category.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Category' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Category.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Category value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Category read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Category instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Category given an JSON string + * + * @param jsonString JSON string + * @return An instance of Category + * @throws IOException if the JSON string is invalid with respect to Category + */ + public static Category fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Category.class); + } + + /** + * Convert an instance of Category to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java new file mode 100644 index 000000000000..054958ab9564 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -0,0 +1,333 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Describes the result of uploading an image resource + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ModelApiResponse { + public static final String SERIALIZED_NAME_CODE = "code"; + @SerializedName(SERIALIZED_NAME_CODE) + @javax.annotation.Nullable + private Integer code; + + public static final String SERIALIZED_NAME_TYPE = "type"; + @SerializedName(SERIALIZED_NAME_TYPE) + @javax.annotation.Nullable + private String type; + + public static final String SERIALIZED_NAME_MESSAGE = "message"; + @SerializedName(SERIALIZED_NAME_MESSAGE) + @javax.annotation.Nullable + private String message; + + public ModelApiResponse() { + } + + public ModelApiResponse code(@javax.annotation.Nullable Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + @javax.annotation.Nullable + + public Integer getCode() { + return code; + } + + public void setCode(@javax.annotation.Nullable Integer code) { + this.code = code; + } + + + public ModelApiResponse type(@javax.annotation.Nullable String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @javax.annotation.Nullable + + public String getType() { + return type; + } + + public void setType(@javax.annotation.Nullable String type) { + this.type = type; + } + + + public ModelApiResponse message(@javax.annotation.Nullable String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + @javax.annotation.Nullable + + public String getMessage() { + return message; + } + + public void setMessage(@javax.annotation.Nullable String message) { + this.message = message; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ModelApiResponse instance itself + */ + public ModelApiResponse putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message)&& + Objects.equals(this.additionalProperties, _apiResponse.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("code", "type", "message")); + + // 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 ModelApiResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); + } + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelApiResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelApiResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelApiResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelApiResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ModelApiResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ModelApiResponse instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ModelApiResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of ModelApiResponse + * @throws IOException if the JSON string is invalid with respect to ModelApiResponse + */ + public static ModelApiResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ModelApiResponse.class); + } + + /** + * Convert an instance of ModelApiResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Order.java new file mode 100644 index 000000000000..83e153dffafc --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Order.java @@ -0,0 +1,471 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * An order for a pets from the pet store + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Order { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_PET_ID = "petId"; + @SerializedName(SERIALIZED_NAME_PET_ID) + @javax.annotation.Nullable + private Long petId; + + public static final String SERIALIZED_NAME_QUANTITY = "quantity"; + @SerializedName(SERIALIZED_NAME_QUANTITY) + @javax.annotation.Nullable + private Integer quantity; + + public static final String SERIALIZED_NAME_SHIP_DATE = "shipDate"; + @SerializedName(SERIALIZED_NAME_SHIP_DATE) + @javax.annotation.Nullable + private OffsetDateTime shipDate; + + /** + * Order Status + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public static final String SERIALIZED_NAME_COMPLETE = "complete"; + @SerializedName(SERIALIZED_NAME_COMPLETE) + @javax.annotation.Nullable + private Boolean complete = false; + + public Order() { + } + + public Order id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Order petId(@javax.annotation.Nullable Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + */ + @javax.annotation.Nullable + + public Long getPetId() { + return petId; + } + + public void setPetId(@javax.annotation.Nullable Long petId) { + this.petId = petId; + } + + + public Order quantity(@javax.annotation.Nullable Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + */ + @javax.annotation.Nullable + + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(@javax.annotation.Nullable Integer quantity) { + this.quantity = quantity; + } + + + public Order shipDate(@javax.annotation.Nullable OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + */ + @javax.annotation.Nullable + + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(@javax.annotation.Nullable OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + + public Order status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + + public Order complete(@javax.annotation.Nullable Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + */ + @javax.annotation.Nullable + + public Boolean getComplete() { + return complete; + } + + public void setComplete(@javax.annotation.Nullable Boolean complete) { + this.complete = complete; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Order instance itself + */ + public Order putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete)&& + Objects.equals(this.additionalProperties, order.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "petId", "quantity", "shipDate", "status", "complete")); + + // 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 Order + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Order.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Order' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Order.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Order value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Order read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Order instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Order given an JSON string + * + * @param jsonString JSON string + * @return An instance of Order + * @throws IOException if the JSON string is invalid with respect to Order + */ + public static Order fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Order.class); + } + + /** + * Convert an instance of Order to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 000000000000..dc4fce54e0e2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,526 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * A pet for sale in the pet store + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Pet { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + @javax.annotation.Nullable + private Category category; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + @javax.annotation.Nonnull + private List photoUrls = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + @javax.annotation.Nullable + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @Deprecated + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public Pet() { + } + + public Pet id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Pet category(@javax.annotation.Nullable Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @javax.annotation.Nullable + + public Category getCategory() { + return category; + } + + public void setCategory(@javax.annotation.Nullable Category category) { + this.category = category; + } + + + public Pet name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public Pet photoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @javax.annotation.Nonnull + + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(@javax.annotation.Nullable List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @javax.annotation.Nullable + + public List getTags() { + return tags; + } + + public void setTags(@javax.annotation.Nullable List tags) { + this.tags = tags; + } + + + @Deprecated + public Pet status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + * @deprecated + */ + @Deprecated + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + @Deprecated + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Pet instance itself + */ + public Pet putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status)&& + Objects.equals(this.additionalProperties, pet.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "category", "name", "photoUrls", "tags", "status")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "photoUrls")); + } + + /** + * 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 Pet + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Pet.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `category` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category")); + } + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // ensure the required json array is present + if (jsonObj.get("photoUrls") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("photoUrls").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); + } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + com.google.gson.JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + }; + } + } + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Pet.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Pet' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Pet.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Pet value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Pet read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Pet instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Pet given an JSON string + * + * @param jsonString JSON string + * @return An instance of Pet + * @throws IOException if the JSON string is invalid with respect to Pet + */ + public static Pet fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Pet.class); + } + + /** + * Convert an instance of Pet to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 000000000000..628aaf4eb272 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,303 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * A tag for a pet + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Tag { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nullable + private String name; + + public Tag() { + } + + public Tag id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Tag name(@javax.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nullable + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nullable String name) { + this.name = name; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Tag instance itself + */ + public Tag putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name)&& + Objects.equals(this.additionalProperties, tag.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name")); + + // 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 Tag + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Tag is not found in the empty JSON string", Tag.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Tag.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Tag' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Tag.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Tag value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Tag read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Tag instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Tag given an JSON string + * + * @param jsonString JSON string + * @return An instance of Tag + * @throws IOException if the JSON string is invalid with respect to Tag + */ + public static Tag fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Tag.class); + } + + /** + * Convert an instance of Tag to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/User.java new file mode 100644 index 000000000000..277482af6fae --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/main/java/org/openapitools/client/model/User.java @@ -0,0 +1,480 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * A User who is purchasing from the pet store + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class User { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_USERNAME = "username"; + @SerializedName(SERIALIZED_NAME_USERNAME) + @javax.annotation.Nullable + private String username; + + public static final String SERIALIZED_NAME_FIRST_NAME = "firstName"; + @SerializedName(SERIALIZED_NAME_FIRST_NAME) + @javax.annotation.Nullable + private String firstName; + + public static final String SERIALIZED_NAME_LAST_NAME = "lastName"; + @SerializedName(SERIALIZED_NAME_LAST_NAME) + @javax.annotation.Nullable + private String lastName; + + public static final String SERIALIZED_NAME_EMAIL = "email"; + @SerializedName(SERIALIZED_NAME_EMAIL) + @javax.annotation.Nullable + private String email; + + public static final String SERIALIZED_NAME_PASSWORD = "password"; + @SerializedName(SERIALIZED_NAME_PASSWORD) + @javax.annotation.Nullable + private String password; + + public static final String SERIALIZED_NAME_PHONE = "phone"; + @SerializedName(SERIALIZED_NAME_PHONE) + @javax.annotation.Nullable + private String phone; + + public static final String SERIALIZED_NAME_USER_STATUS = "userStatus"; + @SerializedName(SERIALIZED_NAME_USER_STATUS) + @javax.annotation.Nullable + private Integer userStatus; + + public User() { + } + + public User id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public User username(@javax.annotation.Nullable String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + */ + @javax.annotation.Nullable + + public String getUsername() { + return username; + } + + public void setUsername(@javax.annotation.Nullable String username) { + this.username = username; + } + + + public User firstName(@javax.annotation.Nullable String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + */ + @javax.annotation.Nullable + + public String getFirstName() { + return firstName; + } + + public void setFirstName(@javax.annotation.Nullable String firstName) { + this.firstName = firstName; + } + + + public User lastName(@javax.annotation.Nullable String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + */ + @javax.annotation.Nullable + + public String getLastName() { + return lastName; + } + + public void setLastName(@javax.annotation.Nullable String lastName) { + this.lastName = lastName; + } + + + public User email(@javax.annotation.Nullable String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + */ + @javax.annotation.Nullable + + public String getEmail() { + return email; + } + + public void setEmail(@javax.annotation.Nullable String email) { + this.email = email; + } + + + public User password(@javax.annotation.Nullable String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + */ + @javax.annotation.Nullable + + public String getPassword() { + return password; + } + + public void setPassword(@javax.annotation.Nullable String password) { + this.password = password; + } + + + public User phone(@javax.annotation.Nullable String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + */ + @javax.annotation.Nullable + + public String getPhone() { + return phone; + } + + public void setPhone(@javax.annotation.Nullable String phone) { + this.phone = phone; + } + + + public User userStatus(@javax.annotation.Nullable Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + */ + @javax.annotation.Nullable + + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(@javax.annotation.Nullable Integer userStatus) { + this.userStatus = userStatus; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the User instance itself + */ + public User putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus)&& + Objects.equals(this.additionalProperties, user.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus")); + + // 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 User + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString())); + } + if ((jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonNull()) && !jsonObj.get("firstName").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `firstName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("firstName").toString())); + } + if ((jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonNull()) && !jsonObj.get("lastName").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `lastName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("lastName").toString())); + } + if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString())); + } + if ((jsonObj.get("password") != null && !jsonObj.get("password").isJsonNull()) && !jsonObj.get("password").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); + } + if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!User.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'User' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(User.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, User value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public User read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + User instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of User given an JSON string + * + * @param jsonString JSON string + * @return An instance of User + * @throws IOException if the JSON string is invalid with respect to User + */ + public static User fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, User.class); + } + + /** + * Convert an instance of User to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 000000000000..0aa0fcd8fdd1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +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 PetApi + */ +@Disabled +public class PetApiTest { + + private final PetApi api = new PetApi(); + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void addPetTest() throws ApiException { + Pet pet = null; + Pet response = api.addPet(pet) + .execute(); + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void deletePetTest() throws ApiException { + Long petId = null; + String apiKey = null; + api.deletePet(petId) + .apiKey(apiKey) + .execute(); + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws ApiException { + List status = null; + List response = api.findPetsByStatus(status) + .execute(); + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws ApiException { + List tags = null; + List response = api.findPetsByTags(tags) + .execute(); + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException if the Api call fails + */ + @Test + public void getPetByIdTest() throws ApiException { + Long petId = null; + Pet response = api.getPetById(petId) + .execute(); + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void updatePetTest() throws ApiException { + Pet pet = null; + Pet response = api.updatePet(pet) + .execute(); + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws ApiException { + Long petId = null; + String name = null; + String status = null; + api.updatePetWithForm(petId, name, status); + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void uploadFileTest() throws ApiException { + Long petId = null; + String additionalMetadata = null; + File _file = null; + ModelApiResponse response = api.uploadFile(petId) + .additionalMetadata(additionalMetadata) + ._file(_file) + .execute(); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 000000000000..1eceae7861ec --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java new file mode 100644 index 000000000000..8f6ae5fee00a --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/OrderTest.java new file mode 100644 index 000000000000..dfb248d79fee --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/OrderTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 000000000000..e739c5684909 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 000000000000..04a45cff9916 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/UserTest.java b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/UserTest.java new file mode 100644 index 000000000000..3041ccbd2602 --- /dev/null +++ b/samples/client/petstore/java/okhttp-group-parameter/src/test/java/org/openapitools/client/model/UserTest.java @@ -0,0 +1,97 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/samples/client/petstore/java/okhttp/.github/workflows/maven.yml b/samples/client/petstore/java/okhttp/.github/workflows/maven.yml new file mode 100644 index 000000000000..460f78bfd1b2 --- /dev/null +++ b/samples/client/petstore/java/okhttp/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build OpenAPI Petstore + runs-on: ubuntu-latest + strategy: + matrix: + java: [ 17, 21 ] + steps: + - uses: actions/checkout@v4 + - name: Set up JDK + uses: actions/setup-java@v4 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml diff --git a/samples/client/petstore/java/okhttp/.gitignore b/samples/client/petstore/java/okhttp/.gitignore new file mode 100644 index 000000000000..a530464afa1b --- /dev/null +++ b/samples/client/petstore/java/okhttp/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# 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 +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/okhttp/.openapi-generator-ignore b/samples/client/petstore/java/okhttp/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/java/okhttp/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/okhttp/.openapi-generator/FILES b/samples/client/petstore/java/okhttp/.openapi-generator/FILES new file mode 100644 index 000000000000..706db8d1eda7 --- /dev/null +++ b/samples/client/petstore/java/okhttp/.openapi-generator/FILES @@ -0,0 +1,279 @@ +.github/workflows/maven.yml +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/AdditionalPropertiesClass.md +docs/AllOfModelArrayAnyOf.md +docs/AllOfModelArrayAnyOfAllOfAttributes.md +docs/AllOfModelArrayAnyOfAllOfAttributesC.md +docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md +docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md +docs/AllOfRefToDouble.md +docs/AllOfRefToFloat.md +docs/AllOfRefToLong.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/Apple.md +docs/AppleReq.md +docs/ArrayAnyOf.md +docs/ArrayDefault.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfInlineAllOf.md +docs/ArrayOfInlineAllOfArrayAllofDogPropertyInner.md +docs/ArrayOfNumberOnly.md +docs/ArrayOneOf.md +docs/ArrayTest.md +docs/Banana.md +docs/BananaReq.md +docs/BasquePig.md +docs/Capitalization.md +docs/Cat.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/ComplexQuadrilateral.md +docs/DanishPig.md +docs/DefaultApi.md +docs/DeprecatedObject.md +docs/Dog.md +docs/Drawing.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumStringDiscriminator.md +docs/EnumTest.md +docs/EquilateralTriangle.md +docs/FakeAnyOfWIthSameErasureGet200Response.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/FakeOneOfWIthSameErasureGet200Response.md +docs/FakeRefParameterPetIdParameter.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FooGetDefaultResponse.md +docs/FormatTest.md +docs/FreeFormObjectTestClass.md +docs/FreeFormObjectTestClassProperties.md +docs/Fruit.md +docs/FruitReq.md +docs/GmFruit.md +docs/GrandparentAnimal.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/IsoscelesTriangle.md +docs/Mammal.md +docs/MammalAnyof.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelApiResponse.md +docs/ModelFile.md +docs/ModelList.md +docs/ModelReturn.md +docs/ModelWithOneOfAnyOfProperties.md +docs/Name.md +docs/NestedArrayWithDefaultValues.md +docs/NewPet.md +docs/NewPetCategoryInlineAllof.md +docs/NewPetCategoryInlineAllofAllOfCategoryTag.md +docs/NullableClass.md +docs/NullableEnum.md +docs/NullableFieldsMapError.md +docs/NullableFieldsMapResponse.md +docs/NullableFieldsMapSuccess.md +docs/NullableFieldsValue.md +docs/NullableShape.md +docs/NumberOnly.md +docs/ObjectWithDeprecatedFields.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/ParentPet.md +docs/Pet.md +docs/PetApi.md +docs/PetComposition.md +docs/PetRef.md +docs/PetUsingAllOf.md +docs/PetWithRequiredTags.md +docs/Pig.md +docs/PropertyNameCollision.md +docs/Quadrilateral.md +docs/QuadrilateralInterface.md +docs/ReadOnlyFirst.md +docs/RequiredNullableBody.md +docs/Scalar.md +docs/ScalarAnyOf.md +docs/ScaleneTriangle.md +docs/Shape.md +docs/ShapeInterface.md +docs/ShapeOrNull.md +docs/SimpleQuadrilateral.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/Tag.md +docs/TestInlineFreeformAdditionalPropertiesRequest.md +docs/Triangle.md +docs/TriangleInterface.md +docs/User.md +docs/UserApi.md +docs/Value.md +docs/ValuesApi.md +docs/Variable.md +docs/Whale.md +docs/Zebra.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiCallback.java +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/ApiException.java +src/main/java/org/openapitools/client/ApiResponse.java +src/main/java/org/openapitools/client/Configuration.java +src/main/java/org/openapitools/client/GzipRequestInterceptor.java +src/main/java/org/openapitools/client/JSON.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/ProgressRequestBody.java +src/main/java/org/openapitools/client/ProgressResponseBody.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/AnotherFakeApi.java +src/main/java/org/openapitools/client/api/DefaultApi.java +src/main/java/org/openapitools/client/api/FakeApi.java +src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +src/main/java/org/openapitools/client/api/PetApi.java +src/main/java/org/openapitools/client/api/StoreApi.java +src/main/java/org/openapitools/client/api/UserApi.java +src/main/java/org/openapitools/client/api/ValuesApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/auth/OAuth.java +src/main/java/org/openapitools/client/auth/OAuthFlow.java +src/main/java/org/openapitools/client/auth/RetryingOAuth.java +src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java +src/main/java/org/openapitools/client/model/AllOfRefToDouble.java +src/main/java/org/openapitools/client/model/AllOfRefToFloat.java +src/main/java/org/openapitools/client/model/AllOfRefToLong.java +src/main/java/org/openapitools/client/model/Animal.java +src/main/java/org/openapitools/client/model/Apple.java +src/main/java/org/openapitools/client/model/AppleReq.java +src/main/java/org/openapitools/client/model/ArrayAnyOf.java +src/main/java/org/openapitools/client/model/ArrayDefault.java +src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java +src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java +src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayOneOf.java +src/main/java/org/openapitools/client/model/ArrayTest.java +src/main/java/org/openapitools/client/model/Banana.java +src/main/java/org/openapitools/client/model/BananaReq.java +src/main/java/org/openapitools/client/model/BasquePig.java +src/main/java/org/openapitools/client/model/Capitalization.java +src/main/java/org/openapitools/client/model/Cat.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/ClassModel.java +src/main/java/org/openapitools/client/model/Client.java +src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java +src/main/java/org/openapitools/client/model/DanishPig.java +src/main/java/org/openapitools/client/model/DeprecatedObject.java +src/main/java/org/openapitools/client/model/Dog.java +src/main/java/org/openapitools/client/model/Drawing.java +src/main/java/org/openapitools/client/model/EnumArrays.java +src/main/java/org/openapitools/client/model/EnumClass.java +src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java +src/main/java/org/openapitools/client/model/EnumTest.java +src/main/java/org/openapitools/client/model/EquilateralTriangle.java +src/main/java/org/openapitools/client/model/FakeAnyOfWIthSameErasureGet200Response.java +src/main/java/org/openapitools/client/model/FakeOneOfWIthSameErasureGet200Response.java +src/main/java/org/openapitools/client/model/FakeRefParameterPetIdParameter.java +src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +src/main/java/org/openapitools/client/model/Foo.java +src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java +src/main/java/org/openapitools/client/model/FormatTest.java +src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java +src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java +src/main/java/org/openapitools/client/model/Fruit.java +src/main/java/org/openapitools/client/model/FruitReq.java +src/main/java/org/openapitools/client/model/GmFruit.java +src/main/java/org/openapitools/client/model/GrandparentAnimal.java +src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +src/main/java/org/openapitools/client/model/HealthCheckResult.java +src/main/java/org/openapitools/client/model/IsoscelesTriangle.java +src/main/java/org/openapitools/client/model/Mammal.java +src/main/java/org/openapitools/client/model/MammalAnyof.java +src/main/java/org/openapitools/client/model/MapTest.java +src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/Model200Response.java +src/main/java/org/openapitools/client/model/ModelApiResponse.java +src/main/java/org/openapitools/client/model/ModelFile.java +src/main/java/org/openapitools/client/model/ModelList.java +src/main/java/org/openapitools/client/model/ModelReturn.java +src/main/java/org/openapitools/client/model/ModelWithOneOfAnyOfProperties.java +src/main/java/org/openapitools/client/model/Name.java +src/main/java/org/openapitools/client/model/NestedArrayWithDefaultValues.java +src/main/java/org/openapitools/client/model/NewPet.java +src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java +src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java +src/main/java/org/openapitools/client/model/NullableClass.java +src/main/java/org/openapitools/client/model/NullableEnum.java +src/main/java/org/openapitools/client/model/NullableFieldsMapError.java +src/main/java/org/openapitools/client/model/NullableFieldsMapResponse.java +src/main/java/org/openapitools/client/model/NullableFieldsMapSuccess.java +src/main/java/org/openapitools/client/model/NullableFieldsValue.java +src/main/java/org/openapitools/client/model/NullableShape.java +src/main/java/org/openapitools/client/model/NumberOnly.java +src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +src/main/java/org/openapitools/client/model/Order.java +src/main/java/org/openapitools/client/model/OuterComposite.java +src/main/java/org/openapitools/client/model/OuterEnum.java +src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java +src/main/java/org/openapitools/client/model/OuterEnumInteger.java +src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java +src/main/java/org/openapitools/client/model/ParentPet.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/PetComposition.java +src/main/java/org/openapitools/client/model/PetRef.java +src/main/java/org/openapitools/client/model/PetUsingAllOf.java +src/main/java/org/openapitools/client/model/PetWithRequiredTags.java +src/main/java/org/openapitools/client/model/Pig.java +src/main/java/org/openapitools/client/model/PropertyNameCollision.java +src/main/java/org/openapitools/client/model/Quadrilateral.java +src/main/java/org/openapitools/client/model/QuadrilateralInterface.java +src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +src/main/java/org/openapitools/client/model/RequiredNullableBody.java +src/main/java/org/openapitools/client/model/Scalar.java +src/main/java/org/openapitools/client/model/ScalarAnyOf.java +src/main/java/org/openapitools/client/model/ScaleneTriangle.java +src/main/java/org/openapitools/client/model/Shape.java +src/main/java/org/openapitools/client/model/ShapeInterface.java +src/main/java/org/openapitools/client/model/ShapeOrNull.java +src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java +src/main/java/org/openapitools/client/model/SpecialModelName.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java +src/main/java/org/openapitools/client/model/Triangle.java +src/main/java/org/openapitools/client/model/TriangleInterface.java +src/main/java/org/openapitools/client/model/User.java +src/main/java/org/openapitools/client/model/Value.java +src/main/java/org/openapitools/client/model/Variable.java +src/main/java/org/openapitools/client/model/Whale.java +src/main/java/org/openapitools/client/model/Zebra.java diff --git a/samples/client/petstore/java/okhttp/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp/.openapi-generator/VERSION new file mode 100644 index 000000000000..84bf2ceeaede --- /dev/null +++ b/samples/client/petstore/java/okhttp/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.28.0-SNAPSHOT diff --git a/samples/client/petstore/java/okhttp/.travis.yml b/samples/client/petstore/java/okhttp/.travis.yml new file mode 100644 index 000000000000..1b6741c083c7 --- /dev/null +++ b/samples/client/petstore/java/okhttp/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/client/petstore/java/okhttp/README.md b/samples/client/petstore/java/okhttp/README.md new file mode 100644 index 000000000000..aabc64de4d9e --- /dev/null +++ b/samples/client/petstore/java/okhttp/README.md @@ -0,0 +1,337 @@ +# petstore-okhttp + +OpenAPI Petstore +- API version: 1.0.0 + - Generator version: 7.28.0-SNAPSHOT + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: +1. Java 1.8+ +2. Maven (3.8.3+)/Gradle (7.2+) + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + petstore-okhttp + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the 'petstore-okhttp' jar has been published to maven central. + mavenLocal() // Needed if the 'petstore-okhttp' jar has been published to the local maven repo. + } + + dependencies { + implementation "org.openapitools:petstore-okhttp:1.0.0" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +* `target/petstore-okhttp-1.0.0.jar` +* `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.call123testSpecialTags(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**call123testSpecialTags**](docs/AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags +*AnotherFakeApi* | [**getParameterArrayNumber**](docs/AnotherFakeApi.md#getParameterArrayNumber) | **GET** /fake/parameter-array-number | parameter array number default value +*AnotherFakeApi* | [**getParameterStringNumber**](docs/AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number +*DefaultApi* | [**fakeAnyOfWIthSameErasureGet**](docs/DefaultApi.md#fakeAnyOfWIthSameErasureGet) | **GET** /fake/anyOfWIthSameErasure | +*DefaultApi* | [**fakeFreeFormQueryParametersGet**](docs/DefaultApi.md#fakeFreeFormQueryParametersGet) | **GET** /fake/free-form-query-parameters | +*DefaultApi* | [**fakeOneOfWIthSameErasureGet**](docs/DefaultApi.md#fakeOneOfWIthSameErasureGet) | **GET** /fake/oneOfWIthSameErasure | +*DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo | +*FakeApi* | [**fakeGetFreeFormObjectGet**](docs/FakeApi.md#fakeGetFreeFormObjectGet) | **GET** /fake/get-free-form-object | +*FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +*FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +*FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +*FakeApi* | [**fakeRefParameter**](docs/FakeApi.md#fakeRefParameter) | **POST** /fake/pet/{petId}/reference/parameter | fake reference parameter +*FakeApi* | [**fakeRequiredNullableBodyGet**](docs/FakeApi.md#fakeRequiredNullableBodyGet) | **GET** /fake/required-nullable-body | fields in the response body, required and nullable are both true +*FakeApi* | [**fakeUploadRefRequestBodies**](docs/FakeApi.md#fakeUploadRefRequestBodies) | **POST** /fake/pet/{petId}/uploadImage | fake reference parameter +*FakeApi* | [**getFakeArrayofenums**](docs/FakeApi.md#getFakeArrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**getFakeHealth**](docs/FakeApi.md#getFakeHealth) | **GET** /fake/health | Health check endpoint +*FakeApi* | [**getParameterNameMapping**](docs/FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties +*FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testGroupParameters**](docs/FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testInlineFreeformAdditionalProperties**](docs/FakeApi.md#testInlineFreeformAdditionalProperties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties +*FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**testNullableRequiredFieldsAnyOf**](docs/FakeApi.md#testNullableRequiredFieldsAnyOf) | **GET** /fake/nullable-required-fields-anyof | test anyOf with map of objects containing nullable required fields +*FakeApi* | [**testQueryParameterCollectionFormat**](docs/FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | +*FakeApi* | [**testStringMapReference**](docs/FakeApi.md#testStringMapReference) | **POST** /fake/stringMap-reference | test referenced string map +*FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**uploadFileWithRequiredFile**](docs/PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user +*ValuesApi* | [**getSomeValues**](docs/ValuesApi.md#getSomeValues) | **GET** /values | Get some primitive variable values + + +## Documentation for Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AllOfModelArrayAnyOf](docs/AllOfModelArrayAnyOf.md) + - [AllOfModelArrayAnyOfAllOfAttributes](docs/AllOfModelArrayAnyOfAllOfAttributes.md) + - [AllOfModelArrayAnyOfAllOfAttributesC](docs/AllOfModelArrayAnyOfAllOfAttributesC.md) + - [AllOfModelArrayAnyOfAllOfLinkListColumn1](docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md) + - [AllOfModelArrayAnyOfAllOfLinkListColumn1Value](docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md) + - [AllOfRefToDouble](docs/AllOfRefToDouble.md) + - [AllOfRefToFloat](docs/AllOfRefToFloat.md) + - [AllOfRefToLong](docs/AllOfRefToLong.md) + - [Animal](docs/Animal.md) + - [Apple](docs/Apple.md) + - [AppleReq](docs/AppleReq.md) + - [ArrayAnyOf](docs/ArrayAnyOf.md) + - [ArrayDefault](docs/ArrayDefault.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfInlineAllOf](docs/ArrayOfInlineAllOf.md) + - [ArrayOfInlineAllOfArrayAllofDogPropertyInner](docs/ArrayOfInlineAllOfArrayAllofDogPropertyInner.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayOneOf](docs/ArrayOneOf.md) + - [ArrayTest](docs/ArrayTest.md) + - [Banana](docs/Banana.md) + - [BananaReq](docs/BananaReq.md) + - [BasquePig](docs/BasquePig.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [ComplexQuadrilateral](docs/ComplexQuadrilateral.md) + - [DanishPig](docs/DanishPig.md) + - [DeprecatedObject](docs/DeprecatedObject.md) + - [Dog](docs/Dog.md) + - [Drawing](docs/Drawing.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumStringDiscriminator](docs/EnumStringDiscriminator.md) + - [EnumTest](docs/EnumTest.md) + - [EquilateralTriangle](docs/EquilateralTriangle.md) + - [FakeAnyOfWIthSameErasureGet200Response](docs/FakeAnyOfWIthSameErasureGet200Response.md) + - [FakeOneOfWIthSameErasureGet200Response](docs/FakeOneOfWIthSameErasureGet200Response.md) + - [FakeRefParameterPetIdParameter](docs/FakeRefParameterPetIdParameter.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [Foo](docs/Foo.md) + - [FooGetDefaultResponse](docs/FooGetDefaultResponse.md) + - [FormatTest](docs/FormatTest.md) + - [FreeFormObjectTestClass](docs/FreeFormObjectTestClass.md) + - [FreeFormObjectTestClassProperties](docs/FreeFormObjectTestClassProperties.md) + - [Fruit](docs/Fruit.md) + - [FruitReq](docs/FruitReq.md) + - [GmFruit](docs/GmFruit.md) + - [GrandparentAnimal](docs/GrandparentAnimal.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [HealthCheckResult](docs/HealthCheckResult.md) + - [IsoscelesTriangle](docs/IsoscelesTriangle.md) + - [Mammal](docs/Mammal.md) + - [MammalAnyof](docs/MammalAnyof.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [ModelFile](docs/ModelFile.md) + - [ModelList](docs/ModelList.md) + - [ModelReturn](docs/ModelReturn.md) + - [ModelWithOneOfAnyOfProperties](docs/ModelWithOneOfAnyOfProperties.md) + - [Name](docs/Name.md) + - [NestedArrayWithDefaultValues](docs/NestedArrayWithDefaultValues.md) + - [NewPet](docs/NewPet.md) + - [NewPetCategoryInlineAllof](docs/NewPetCategoryInlineAllof.md) + - [NewPetCategoryInlineAllofAllOfCategoryTag](docs/NewPetCategoryInlineAllofAllOfCategoryTag.md) + - [NullableClass](docs/NullableClass.md) + - [NullableEnum](docs/NullableEnum.md) + - [NullableFieldsMapError](docs/NullableFieldsMapError.md) + - [NullableFieldsMapResponse](docs/NullableFieldsMapResponse.md) + - [NullableFieldsMapSuccess](docs/NullableFieldsMapSuccess.md) + - [NullableFieldsValue](docs/NullableFieldsValue.md) + - [NullableShape](docs/NullableShape.md) + - [NumberOnly](docs/NumberOnly.md) + - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) + - [OuterEnumInteger](docs/OuterEnumInteger.md) + - [OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) + - [ParentPet](docs/ParentPet.md) + - [Pet](docs/Pet.md) + - [PetComposition](docs/PetComposition.md) + - [PetRef](docs/PetRef.md) + - [PetUsingAllOf](docs/PetUsingAllOf.md) + - [PetWithRequiredTags](docs/PetWithRequiredTags.md) + - [Pig](docs/Pig.md) + - [PropertyNameCollision](docs/PropertyNameCollision.md) + - [Quadrilateral](docs/Quadrilateral.md) + - [QuadrilateralInterface](docs/QuadrilateralInterface.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [RequiredNullableBody](docs/RequiredNullableBody.md) + - [Scalar](docs/Scalar.md) + - [ScalarAnyOf](docs/ScalarAnyOf.md) + - [ScaleneTriangle](docs/ScaleneTriangle.md) + - [Shape](docs/Shape.md) + - [ShapeInterface](docs/ShapeInterface.md) + - [ShapeOrNull](docs/ShapeOrNull.md) + - [SimpleQuadrilateral](docs/SimpleQuadrilateral.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) + - [Triangle](docs/Triangle.md) + - [TriangleInterface](docs/TriangleInterface.md) + - [User](docs/User.md) + - [Value](docs/Value.md) + - [Variable](docs/Variable.md) + - [Whale](docs/Whale.md) + - [Zebra](docs/Zebra.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + + +### http_basic_test + +- **Type**: HTTP basic authentication + + +### bearer_test + +- **Type**: HTTP Bearer Token authentication (JWT) + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + + + diff --git a/samples/client/petstore/java/okhttp/api/openapi.yaml b/samples/client/petstore/java/okhttp/api/openapi.yaml new file mode 100644 index 000000000000..55552d3bd480 --- /dev/null +++ b/samples/client/petstore/java/okhttp/api/openapi.yaml @@ -0,0 +1,3332 @@ +openapi: 3.0.0 +info: + description: "This spec is mainly for testing Petstore server and contains fake\ + \ endpoints, models. Please do not use this for any other purpose. Special characters:\ + \ \" \\" + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +servers: +- description: petstore server + url: "http://{server}.swagger.io:{port}/v2" + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: "https://localhost:8080/{version}" + variables: + version: + default: v2 + enum: + - v1 + - v2 +- description: The local server without variables + url: https://127.0.0.1/no_variable +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /foo: + get: + responses: + default: + content: + application/json: + schema: + $ref: "#/components/schemas/_foo_get_default_response" + description: response + x-accepts: + - application/json + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: "#/components/requestBodies/Pet" + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + x-content-type: application/json + x-accepts: + - application/json + put: + description: "" + operationId: updatePet + requestBody: + $ref: "#/components/requestBodies/Pet" + responses: + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + x-content-type: application/json + x-accepts: + - application/json + servers: + - url: http://petstore.swagger.io/v2 + - url: http://path-server-test.petstore.local/v2 + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - deprecated: true + description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + default: [] + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + default: [] + items: + $ref: "#/components/schemas/Pet" + type: array + application/json: + schema: + default: [] + items: + $ref: "#/components/schemas/Pet" + type: array + description: successful operation + "400": + description: Invalid status value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by status + tags: + - pet + x-accepts: + - application/json + - application/xml + /pet/findByTags: + get: + deprecated: true + description: "Multiple tags can be provided with comma separated strings. Use\ + \ tag1, tag2, tag3 for testing." + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + default: [] + items: + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + default: [] + items: + $ref: "#/components/schemas/Pet" + type: array + application/json: + schema: + default: [] + items: + $ref: "#/components/schemas/Pet" + type: array + description: successful operation + "400": + description: Invalid tag value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by tags + tags: + - pet + x-accepts: + - application/json + - application/xml + /pet/{petId}: + delete: + description: "" + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + x-accepts: + - application/json + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/Pet" + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Pet" + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + x-accepts: + - application/json + - application/xml + post: + description: "" + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/updatePetWithForm_request" + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + x-content-type: application/x-www-form-urlencoded + x-accepts: + - application/json + /pet/{petId}/uploadImage: + post: + description: "" + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + - description: Content type header parameter + explode: false + in: header + name: Content-Type + required: false + schema: + type: string + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/uploadFile_request" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + x-content-type: multipart/form-data + x-accepts: + - application/json + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + default: [] + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + x-accepts: + - application/json + /store/order: + post: + description: "" + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/Order" + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/Order" + application/json: + schema: + $ref: "#/components/schemas/Order" + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + x-content-type: application/json + x-accepts: + - application/json + - application/xml + /store/order/{order_id}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: order_id + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + x-accepts: + - application/json + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generate exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: order_id + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/Order" + application/json: + schema: + $ref: "#/components/schemas/Order" + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + x-accepts: + - application/json + - application/xml + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/User" + description: Created user object + required: true + responses: + default: + description: successful operation + summary: Create user + tags: + - user + x-content-type: application/json + x-accepts: + - application/json + /user/createWithArray: + post: + description: "" + operationId: createUsersWithArrayInput + requestBody: + $ref: "#/components/requestBodies/UserArray" + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: + - application/json + /user/createWithList: + post: + description: "" + operationId: createUsersWithListInput + requestBody: + $ref: "#/components/requestBodies/UserArray" + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-content-type: application/json + x-accepts: + - application/json + /user/login: + get: + description: "" + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when token expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + x-accepts: + - application/json + - application/xml + /user/logout: + get: + description: "" + operationId: logoutUser + responses: + default: + description: successful operation + summary: Logs out current logged in user session + tags: + - user + x-accepts: + - application/json + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Delete user + tags: + - user + x-accepts: + - application/json + get: + description: "" + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: "#/components/schemas/User" + application/json: + schema: + $ref: "#/components/schemas/User" + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + x-accepts: + - application/json + - application/xml + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/User" + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + summary: Updated user + tags: + - user + x-content-type: application/json + x-accepts: + - application/json + /fake_classname_test: + patch: + description: To test class name in snake case + operationId: testClassname + requestBody: + $ref: "#/components/requestBodies/Client" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Client" + description: successful operation + security: + - api_key_query: [] + summary: To test class name in snake case + tags: + - fake_classname_tags 123#$%^ + x-content-type: application/json + x-accepts: + - application/json + /fake: + delete: + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + parameters: + - description: Required String in group parameters + explode: true + in: query + name: required_string_group + required: true + schema: + type: integer + style: form + - description: Required Boolean in group parameters + explode: false + in: header + name: required_boolean_group + required: true + schema: + type: boolean + style: simple + - description: Required Integer in group parameters + explode: true + in: query + name: required_int64_group + required: true + schema: + format: int64 + type: integer + style: form + - description: String in group parameters + explode: true + in: query + name: string_group + required: false + schema: + type: integer + style: form + - description: Boolean in group parameters + explode: false + in: header + name: boolean_group + required: false + schema: + type: boolean + style: simple + - description: Integer in group parameters + explode: true + in: query + name: int64_group + required: false + schema: + format: int64 + type: integer + style: form + responses: + "400": + description: Something wrong + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + tags: + - fake + x-group-parameters: true + x-accepts: + - application/json + get: + description: To test enum parameters + operationId: testEnumParameters + parameters: + - description: Header parameter enum test (string array) + explode: false + in: header + name: enum_header_string_array + required: false + schema: + default: [] + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: simple + - description: Header parameter enum test (string) + explode: false + in: header + name: enum_header_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: simple + - description: Query parameter enum test (string array) + explode: true + in: query + name: enum_query_string_array + required: false + schema: + default: [] + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: form + - description: Query parameter enum test (string) + explode: true + in: query + name: enum_query_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_integer + required: false + schema: + enum: + - 1 + - -2 + format: int32 + type: integer + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_double + required: false + schema: + enum: + - 1.1 + - -1.2 + format: double + type: number + style: form + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/testEnumParameters_request" + responses: + "400": + description: Invalid request + "404": + description: Not found + summary: To test enum parameters + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: + - application/json + patch: + description: To test "client" model + operationId: testClientModel + requestBody: + $ref: "#/components/requestBodies/Client" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Client" + description: successful operation + summary: To test "client" model + tags: + - fake + x-content-type: application/json + x-accepts: + - application/json + post: + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/testEndpointParameters_request" + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - http_basic_test: [] + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: + - application/json + /fake/outer/number: + post: + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/OuterNumber" + description: Input number as post body + responses: + "200": + content: + '*/*': + schema: + $ref: "#/components/schemas/OuterNumber" + description: Output number + tags: + - fake + x-content-type: application/json + x-accepts: + - '*/*' + /fake/outer/string: + post: + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/OuterString" + description: Input string as post body + responses: + "200": + content: + '*/*': + schema: + $ref: "#/components/schemas/OuterString" + description: Output string + tags: + - fake + x-content-type: application/json + x-accepts: + - '*/*' + /fake/outer/boolean: + post: + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/OuterBoolean" + description: Input boolean as post body + responses: + "200": + content: + '*/*': + schema: + $ref: "#/components/schemas/OuterBoolean" + description: Output boolean + tags: + - fake + x-content-type: application/json + x-accepts: + - '*/*' + /fake/outer/composite: + post: + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/OuterComposite" + description: Input composite as post body + responses: + "200": + content: + '*/*': + schema: + $ref: "#/components/schemas/OuterComposite" + description: Output composite + tags: + - fake + x-content-type: application/json + x-accepts: + - '*/*' + /fake/jsonFormData: + get: + description: "" + operationId: testJsonFormData + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: "#/components/schemas/testJsonFormData_request" + responses: + "200": + description: successful operation + summary: test json serialization of form data + tags: + - fake + x-content-type: application/x-www-form-urlencoded + x-accepts: + - application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/FreeFormObject" + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: + - application/json + /fake/oneOfWIthSameErasure: + get: + description: "Test route, this shouldn't cause a compiler error" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/_fake_oneOfWIthSameErasure_get_200_response" + description: successful response + x-accepts: + - application/json + /fake/nullable-required-fields-anyof: + get: + description: "Tests that anyOf deserialization works when object values contain\ + \ required fields that are nullable (e.g. Record)" + operationId: testNullableRequiredFieldsAnyOf + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/NullableFieldsMapResponse" + description: successful operation + summary: test anyOf with map of objects containing nullable required fields + tags: + - fake + x-accepts: + - application/json + /fake/anyOfWIthSameErasure: + get: + description: "Test route, this shouldn't cause a compiler error" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/_fake_anyOfWIthSameErasure_get_200_response" + description: successful response + x-accepts: + - application/json + /fake/stringMap-reference: + post: + description: "" + operationId: testStringMapReference + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/MapOfString" + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced string map + tags: + - fake + x-content-type: application/json + x-accepts: + - application/json + /fake/inline-additionalProperties: + post: + description: "" + operationId: testInlineAdditionalProperties + requestBody: + content: + application/json: + schema: + additionalProperties: + type: string + default: [] + type: object + description: request body + required: true + responses: + "200": + description: successful operation + summary: test inline additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: + - application/json + /fake/inline-freeform-additionalProperties: + post: + description: "" + operationId: testInlineFreeformAdditionalProperties + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/testInlineFreeformAdditionalProperties_request" + description: request body + required: true + responses: + "200": + description: successful operation + summary: test inline free-form additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: + - application/json + /fake/body-with-query-params: + put: + operationId: testBodyWithQueryParams + parameters: + - explode: true + in: query + name: query + required: true + schema: + type: string + style: form + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/User" + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: application/json + x-accepts: + - application/json + /another-fake/dummy: + patch: + description: To test special tags and operation ID starting with number + operationId: 123_test_@#$%_special_tags + requestBody: + $ref: "#/components/requestBodies/Client" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Client" + description: successful operation + summary: To test special tags + tags: + - $another-fake? + x-content-type: application/json + x-accepts: + - application/json + /fake/body-with-file-schema: + put: + description: "For this test, the body for this request much reference a schema\ + \ named `File`." + operationId: testBodyWithFileSchema + requestBody: + content: + application/json: + schema: + $ref: "#/components/schemas/FileSchemaTestClass" + required: true + responses: + "200": + description: Success + tags: + - fake + x-content-type: application/json + x-accepts: + - application/json + /fake/get-free-form-object: + get: + description: Get a free form object or Json string + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/FreeFormObjectTestClass" + description: Success + tags: + - fake + x-accepts: + - application/json + /fake/free-form-query-parameters: + get: + parameters: + - explode: true + in: query + name: fixed + required: false + schema: + type: string + style: form + - explode: true + in: query + name: free-form + required: false + schema: + type: object + style: form + responses: + "200": + description: OK + x-accepts: + - application/json + /fake/test-query-parameters: + put: + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - explode: true + in: query + name: pipe + required: true + schema: + default: [] + items: + type: string + type: array + style: form + - explode: false + in: query + name: ioutil + required: true + schema: + default: [] + items: + type: string + type: array + style: form + - explode: false + in: query + name: http + required: true + schema: + default: [] + items: + type: string + type: array + style: spaceDelimited + - explode: false + in: query + name: url + required: true + schema: + default: [] + items: + type: string + type: array + style: form + - explode: true + in: query + name: context + required: true + schema: + default: [] + items: + type: string + type: array + style: form + responses: + "200": + description: Success + tags: + - fake + x-accepts: + - application/json + /fake/{petId}/uploadImageWithRequiredFile: + post: + description: "" + operationId: uploadFileWithRequiredFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/uploadFileWithRequiredFile_request" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image (required) + tags: + - pet + x-content-type: multipart/form-data + x-accepts: + - application/json + /fake/health: + get: + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/HealthCheckResult" + description: The instance started successfully + summary: Health check endpoint + tags: + - fake + x-accepts: + - application/json + /fake/array-of-enums: + get: + operationId: getArrayOfEnums + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ArrayOfEnums" + description: Got named array of enums + summary: Array of Enums + tags: + - fake + x-accepts: + - application/json + /fake/parameter-name-mapping: + get: + operationId: getParameterNameMapping + parameters: + - description: _type + explode: false + in: header + name: _type + required: true + schema: + format: int64 + type: integer + style: simple + - description: type + explode: true + in: query + name: type + required: true + schema: + type: string + style: form + - description: type_ + explode: false + in: header + name: type_ + required: true + schema: + type: string + style: simple + responses: + "200": + description: OK + summary: parameter name mapping test + tags: + - fake + x-accepts: + - application/json + /fake/parameter-string-number: + get: + operationId: getParameterStringNumber + parameters: + - description: string number + explode: false + in: header + name: string_number + required: true + schema: + format: number + type: string + style: simple + responses: + "200": + description: OK + summary: parameter string number + tags: + - another_fake + x-accepts: + - application/json + /fake/parameter-array-number: + get: + operationId: getParameterArrayNumber + parameters: + - description: array integer + explode: false + in: header + name: array + required: true + schema: + default: + - 1 + items: + type: integer + type: array + style: simple + responses: + "200": + description: OK + summary: parameter array number default value + tags: + - another_fake + x-accepts: + - application/json + /fake/pet/{petId}/uploadImage: + post: + description: "" + operationId: fake-upload-ref-request-bodies + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: "#/components/requestBodies/upload_body" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: fake reference parameter + tags: + - fake + x-content-type: multipart/form-data + x-accepts: + - application/json + /fake/pet/{petId}/reference/parameter: + post: + description: "" + operationId: fake-ref-parameter + parameters: + - description: to test oneOf in parameter $ref + explode: false + in: path + name: petId + required: true + schema: + $ref: "#/components/schemas/fake_ref_parameter_petId_parameter" + style: simple + responses: + "200": + description: successful operation + summary: fake reference parameter + tags: + - fake + x-accepts: + - application/json + /values: + get: + description: "" + operationId: getSomeValues + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Variable" + description: successful operation + "400": + description: Invalid Value + summary: Get some primitive variable values + tags: + - values + x-accepts: + - application/json + /internal/only: + get: + description: "" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/Variable" + description: successful operation + "400": + description: Invalid Value + summary: internal only + tags: + - values + x-internal: true + x-accepts: + - application/json + /fake/required-nullable-body: + get: + description: "" + responses: + "200": + content: + application/json: + schema: + $ref: "#/components/schemas/RequiredNullableBody" + description: success + summary: "fields in the response body, required and nullable are both true" + tags: + - fake + x-accepts: + - application/json +components: + parameters: + pet_id: + description: to test oneOf in parameter $ref + explode: false + in: path + name: petId + required: true + schema: + $ref: "#/components/schemas/fake_ref_parameter_petId_parameter" + style: simple + requestBodies: + upload_body: + content: + multipart/form-data: + schema: + $ref: "#/components/schemas/uploadFile_request" + UserArray: + content: + application/json: + examples: + simple-list: + description: Should not get into code examples + summary: Simple list example + value: + - username: foo + - username: bar + schema: + default: [] + items: + $ref: "#/components/schemas/User" + type: array + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: "#/components/schemas/Client" + description: client model + required: true + Pet: + content: + application/json: + schema: + allOf: + - $ref: "#/components/schemas/Pet" + application/xml: + schema: + $ref: "#/components/schemas/Pet" + description: Pet object that needs to be added to the store + required: true + schemas: + Foo: + example: + bar: bar + properties: + bar: + default: bar + type: string + type: object + Bar: + default: bar + type: string + Order: + example: + id: 0 + petId: 6 + quantity: 1 + shipDate: 2020-02-02T20:20:20.000222Z + status: placed + complete: false + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + example: 2020-02-02T20:20:20.000222Z + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + type: object + xml: + name: Order + Category: + example: + id: 6 + name: default-name + properties: + id: + format: int64 + type: integer + name: + default: default-name + type: string + required: + - name + type: object + xml: + name: Category + User: + example: + id: 0 + username: username + firstName: firstName + lastName: lastName + email: email + password: password + phone: phone + userStatus: 6 + objectWithNoDeclaredProps: {} + objectWithNoDeclaredPropsNullable: {} + anyTypeProp: "" + anyTypePropNullable: "" + properties: + id: + format: int64 + type: integer + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + objectWithNoDeclaredProps: + description: test code generation for objects Value must be a map of strings + to values. It cannot be the 'null' value. + type: object + objectWithNoDeclaredPropsNullable: + description: test code generation for nullable objects. Value must be a + map of strings to values or the 'null' value. + nullable: true + type: object + anyTypeProp: + description: "test code generation for any type Here the 'type' attribute\ + \ is not specified, which means the value can be anything, including the\ + \ null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389" + anyTypePropNullable: + description: "test code generation for any type Here the 'type' attribute\ + \ is not specified, which means the value can be anything, including the\ + \ null value, string, number, boolean, array or object. The 'nullable'\ + \ attribute does not change the allowed values." + nullable: true + type: object + xml: + name: User + Tag: + example: + id: 1 + name: name + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: Tag + Pet: + example: + id: 0 + category: + id: 6 + name: default-name + name: doggie + photoUrls: + - photoUrls + - photoUrls + tags: + - id: 1 + name: name + - id: 1 + name: name + status: available + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + $ref: "#/components/schemas/Category" + name: + example: doggie + type: string + photoUrls: + default: [] + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + default: [] + items: + $ref: "#/components/schemas/Tag" + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: Pet + ApiResponse: + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + type: object + Return: + description: Model for testing reserved words + properties: + return: + format: int32 + type: integer + xml: + name: Return + Name: + description: Model for testing model name same as property name + properties: + name: + format: int32 + type: integer + snake_case: + format: int32 + readOnly: true + type: integer + property: + type: string + "123Number": + readOnly: true + type: integer + required: + - name + xml: + name: Name + "200_response": + description: Model for testing model name starting with number + properties: + name: + format: int32 + type: integer + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: "#/components/schemas/Animal" + - properties: + breed: + type: string + type: object + Cat: + allOf: + - $ref: "#/components/schemas/Animal" + - $ref: "#/components/schemas/Address" + - properties: + declawed: + type: boolean + type: object + Address: + additionalProperties: + type: integer + default: [] + type: object + Animal: + discriminator: + propertyName: className + properties: + className: + type: string + color: + default: red + type: string + required: + - className + type: object + AnimalFarm: + items: + $ref: "#/components/schemas/Animal" + type: array + format_test: + properties: + integer: + maximum: 100 + minimum: 10 + multipleOf: 2 + type: integer + int32: + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + format: int64 + type: integer + number: + maximum: 543.2 + minimum: 32.1 + multipleOf: 32.5 + type: number + float: + format: float + maximum: 987.6 + minimum: 54.3 + type: number + double: + format: double + maximum: 123.4 + minimum: 67.8 + type: number + decimal: + format: number + type: string + string: + pattern: "/[a-z]/i" + type: string + byte: + format: byte + type: string + binary: + format: binary + type: string + date: + example: 2020-02-02 + format: date + type: string + dateTime: + example: 2007-12-03T10:15:30+01:00 + format: date-time + type: string + uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string + uuid_with_default: + default: 11111111-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string + password: + format: password + maxLength: 64 + minLength: 10 + type: string + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + pattern: "^\\d{10}$" + type: string + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one + to three digits following i.e. Image_01. + pattern: "/^image_\\d{1,3}$/i" + type: string + required: + - byte + - date + - number + - password + type: object + EnumClass: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + Enum_Test: + properties: + enum_string: + enum: + - UPPER + - lower + - "" + type: string + enum_string_required: + enum: + - UPPER + - lower + - "" + type: string + enum_integer: + enum: + - 1 + - -1 + format: int32 + type: integer + enum_integer_only: + enum: + - 2 + - -2 + type: integer + enum_number: + enum: + - 1.1 + - -1.2 + format: double + type: number + outerEnum: + $ref: "#/components/schemas/OuterEnum" + outerEnumInteger: + $ref: "#/components/schemas/OuterEnumInteger" + outerEnumDefaultValue: + $ref: "#/components/schemas/OuterEnumDefaultValue" + outerEnumIntegerDefaultValue: + $ref: "#/components/schemas/OuterEnumIntegerDefaultValue" + required: + - enum_string_required + type: object + AdditionalPropertiesClass: + properties: + map_property: + additionalProperties: + type: string + default: [] + type: object + map_of_map_property: + additionalProperties: + additionalProperties: + type: string + default: [] + type: object + default: [] + type: object + anytype_1: {} + map_with_undeclared_properties_anytype_1: + type: object + map_with_undeclared_properties_anytype_2: + properties: {} + type: object + map_with_undeclared_properties_anytype_3: + additionalProperties: true + default: [] + type: object + empty_map: + additionalProperties: false + description: "an object with no declared properties and no undeclared properties,\ + \ hence it's an empty map." + type: object + map_with_undeclared_properties_string: + additionalProperties: + type: string + default: [] + type: object + type: object + MixedPropertiesAndAdditionalPropertiesClass: + properties: + uuid: + format: uuid + type: string + dateTime: + format: date-time + type: string + map: + additionalProperties: + $ref: "#/components/schemas/Animal" + default: [] + type: object + type: object + List: + properties: + "123-list": + type: string + type: object + Client: + example: + client: client + properties: + client: + type: string + type: object + ReadOnlyFirst: + properties: + bar: + readOnly: true + type: string + baz: + type: string + type: object + hasOnlyReadOnly: + properties: + bar: + readOnly: true + type: string + foo: + readOnly: true + type: string + type: object + Capitalization: + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + type: object + MapTest: + properties: + map_map_of_string: + additionalProperties: + additionalProperties: + type: string + default: [] + type: object + default: [] + type: object + map_of_enum_string: + additionalProperties: + enum: + - UPPER + - lower + type: string + default: [] + type: object + direct_map: + additionalProperties: + type: boolean + default: [] + type: object + indirect_map: + additionalProperties: + type: boolean + default: [] + type: object + type: object + ArrayTest: + properties: + array_of_string: + default: [] + items: + type: string + type: array + array_array_of_integer: + default: [] + items: + default: [] + items: + format: int64 + type: integer + type: array + type: array + array_array_of_model: + default: [] + items: + default: [] + items: + $ref: "#/components/schemas/ReadOnlyFirst" + type: array + type: array + type: object + NumberOnly: + properties: + JustNumber: + type: number + type: object + ArrayOfNumberOnly: + properties: + ArrayNumber: + default: [] + items: + type: number + type: array + type: object + ArrayOfArrayOfNumberOnly: + properties: + ArrayArrayNumber: + default: [] + items: + default: [] + items: + type: number + type: array + type: array + type: object + EnumArrays: + properties: + just_symbol: + enum: + - '>=' + - $ + type: string + array_enum: + default: [] + items: + enum: + - fish + - crab + type: string + type: array + type: object + FreeFormObject: + additionalProperties: true + default: [] + description: A schema consisting only of additional properties + type: object + MapOfString: + additionalProperties: + type: string + default: [] + description: A schema consisting only of additional properties of type string + type: object + OuterEnum: + enum: + - placed + - approved + - delivered + - s + - S + nullable: true + type: string + OuterEnumInteger: + deprecated: true + enum: + - 0 + - 1 + - 2 + type: integer + OuterEnumDefaultValue: + default: placed + enum: + - placed + - approved + - delivered + type: string + OuterEnumIntegerDefaultValue: + default: 0 + enum: + - 0 + - 1 + - 2 + type: integer + OuterComposite: + example: + my_number: 0.8008281904610115 + my_string: my_string + my_boolean: true + properties: + my_number: + type: number + my_string: + type: string + my_boolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + type: object + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + default: [] + type: object + FileSchemaTestClass: + example: + file: + sourceURI: sourceURI + files: + - sourceURI: sourceURI + - sourceURI: sourceURI + properties: + file: + $ref: "#/components/schemas/File" + files: + default: [] + items: + $ref: "#/components/schemas/File" + type: array + type: object + FreeFormObjectTestClass: + example: + name: name + properties: FreeFormObjectTestClass_properties + properties: + name: + type: string + properties: + $ref: "#/components/schemas/FreeFormObjectTestClass_properties" + type: object + File: + description: Must be named `File` for test. + example: + sourceURI: sourceURI + properties: + sourceURI: + description: Test capitalization + type: string + type: object + _special_model.name_: + properties: + $special[property.name]: + format: int64 + type: integer + _special_model.name_: + type: string + xml: + name: "$special[model.name]" + HealthCheckResult: + description: Just a string to inform instance is up and running. Make it nullable + in hope to get it as pointer in generated model. + example: + NullableMessage: NullableMessage + properties: + NullableMessage: + nullable: true + type: string + type: object + NullableClass: + additionalProperties: + nullable: true + type: object + properties: + integer_prop: + nullable: true + type: integer + number_prop: + nullable: true + type: number + boolean_prop: + nullable: true + type: boolean + string_prop: + nullable: true + type: string + date_prop: + format: date + nullable: true + type: string + datetime_prop: + format: date-time + nullable: true + type: string + array_nullable_prop: + items: + type: object + nullable: true + type: array + array_and_items_nullable_prop: + items: + nullable: true + type: object + nullable: true + type: array + array_items_nullable: + default: [] + items: + nullable: true + type: object + type: array + object_nullable_prop: + additionalProperties: + type: object + nullable: true + type: object + object_and_items_nullable_prop: + additionalProperties: + nullable: true + type: object + nullable: true + type: object + object_items_nullable: + additionalProperties: + nullable: true + type: object + default: [] + type: object + type: object + fruit: + additionalProperties: false + oneOf: + - $ref: "#/components/schemas/apple" + - $ref: "#/components/schemas/banana" + properties: + color: + type: string + apple: + nullable: true + properties: + cultivar: + pattern: "^[a-zA-Z\\s]*$" + type: string + origin: + pattern: "/^[A-Z\\s]*$/i" + type: string + type: object + banana: + properties: + lengthCm: + type: number + type: object + mammal: + discriminator: + propertyName: className + oneOf: + - $ref: "#/components/schemas/whale" + - $ref: "#/components/schemas/zebra" + - $ref: "#/components/schemas/Pig" + mammal_anyof: + anyOf: + - $ref: "#/components/schemas/whale" + - $ref: "#/components/schemas/zebra" + - $ref: "#/components/schemas/Pig" + discriminator: + propertyName: className + whale: + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + required: + - className + type: object + zebra: + additionalProperties: true + properties: + type: + enum: + - plains + - mountain + - grevys + type: string + className: + type: string + required: + - className + type: object + Pig: + discriminator: + propertyName: className + oneOf: + - $ref: "#/components/schemas/BasquePig" + - $ref: "#/components/schemas/DanishPig" + BasquePig: + properties: + className: + type: string + required: + - className + type: object + DanishPig: + properties: + className: + type: string + required: + - className + type: object + gmFruit: + additionalProperties: false + anyOf: + - $ref: "#/components/schemas/apple" + - $ref: "#/components/schemas/banana" + properties: + color: + type: string + fruitReq: + additionalProperties: false + nullable: true + oneOf: + - $ref: "#/components/schemas/appleReq" + - $ref: "#/components/schemas/bananaReq" + appleReq: + additionalProperties: false + properties: + cultivar: + type: string + mealy: + type: boolean + required: + - cultivar + type: object + bananaReq: + additionalProperties: false + properties: + lengthCm: + type: number + sweet: + type: boolean + required: + - lengthCm + type: object + Drawing: + additionalProperties: + $ref: "#/components/schemas/fruit" + properties: + mainShape: + $ref: "#/components/schemas/Shape" + shapeOrNull: + $ref: "#/components/schemas/ShapeOrNull" + nullableShape: + $ref: "#/components/schemas/NullableShape" + shapes: + default: [] + items: + $ref: "#/components/schemas/Shape" + type: array + type: object + Shape: + discriminator: + propertyName: shapeType + oneOf: + - $ref: "#/components/schemas/Triangle" + - $ref: "#/components/schemas/Quadrilateral" + ShapeOrNull: + description: The value may be a shape or the 'null' value. This is introduced + in OAS schema >= 3.1. + discriminator: + propertyName: shapeType + nullable: true + oneOf: + - $ref: "#/components/schemas/Triangle" + - $ref: "#/components/schemas/Quadrilateral" + NullableShape: + description: The value may be a shape or the 'null' value. The 'nullable' attribute + was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema + >= 3.1. + discriminator: + propertyName: shapeType + nullable: true + oneOf: + - $ref: "#/components/schemas/Triangle" + - $ref: "#/components/schemas/Quadrilateral" + ShapeInterface: + properties: + shapeType: + type: string + required: + - shapeType + TriangleInterface: + properties: + triangleType: + type: string + required: + - triangleType + Triangle: + discriminator: + propertyName: triangleType + oneOf: + - $ref: "#/components/schemas/EquilateralTriangle" + - $ref: "#/components/schemas/IsoscelesTriangle" + - $ref: "#/components/schemas/ScaleneTriangle" + EquilateralTriangle: + allOf: + - $ref: "#/components/schemas/ShapeInterface" + - $ref: "#/components/schemas/TriangleInterface" + IsoscelesTriangle: + additionalProperties: false + allOf: + - $ref: "#/components/schemas/ShapeInterface" + - $ref: "#/components/schemas/TriangleInterface" + ScaleneTriangle: + allOf: + - $ref: "#/components/schemas/ShapeInterface" + - $ref: "#/components/schemas/TriangleInterface" + QuadrilateralInterface: + properties: + quadrilateralType: + type: string + required: + - quadrilateralType + Quadrilateral: + discriminator: + propertyName: quadrilateralType + oneOf: + - $ref: "#/components/schemas/SimpleQuadrilateral" + - $ref: "#/components/schemas/ComplexQuadrilateral" + SimpleQuadrilateral: + allOf: + - $ref: "#/components/schemas/ShapeInterface" + - $ref: "#/components/schemas/QuadrilateralInterface" + ComplexQuadrilateral: + allOf: + - $ref: "#/components/schemas/ShapeInterface" + - $ref: "#/components/schemas/QuadrilateralInterface" + GrandparentAnimal: + discriminator: + propertyName: pet_type + properties: + pet_type: + type: string + required: + - pet_type + type: object + ParentPet: + allOf: + - $ref: "#/components/schemas/GrandparentAnimal" + type: object + ArrayOfEnums: + default: [] + items: + $ref: "#/components/schemas/OuterEnum" + type: array + DateTimeTest: + default: 2010-01-01T10:10:10.000111+01:00 + example: 2010-01-01T10:10:10.000111+01:00 + format: date-time + type: string + DeprecatedObject: + deprecated: true + properties: + name: + type: string + type: object + ObjectWithDeprecatedFields: + properties: + uuid: + type: string + id: + deprecated: true + type: number + deprecatedRef: + $ref: "#/components/schemas/DeprecatedObject" + bars: + default: [] + deprecated: true + items: + $ref: "#/components/schemas/Bar" + type: array + type: object + PetWithRequiredTags: + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + $ref: "#/components/schemas/Category" + name: + example: doggie + type: string + photoUrls: + default: [] + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + default: [] + items: + $ref: "#/components/schemas/Tag" + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + - tags + type: object + xml: + name: Pet + ArrayOfInlineAllOf: + properties: + id: + format: int64 + type: integer + name: + example: doggie + type: string + array_allof_dog_property: + default: [] + items: + $ref: "#/components/schemas/ArrayOfInlineAllOf_array_allof_dog_property_inner" + type: array + required: + - name + type: object + EnumStringDiscriminator: + description: An object to test discriminator of enum string + discriminator: + propertyName: enum_str_type + properties: + enum_str_type: + description: enum string type + enum: + - type_a + - type_b + type: string + required: + - enum_str_type + type: object + ArrayDefault: + properties: + WithDefaultEmptyBracket: + default: [] + items: + type: string + type: array + WithoutDefault: + default: [] + items: + type: string + type: array + Variable: + description: Value object + example: + name: variable_1 + value: 046b6c7f-0b8a-43b9-b35d-6489e6daee91 + properties: + name: + example: variable_1 + type: string + value: + $ref: "#/components/schemas/Value" + required: + - name + - value + Value: + oneOf: + - $ref: "#/components/schemas/Scalar" + - $ref: "#/components/schemas/Array" + Scalar: + description: Values of scalar type + oneOf: + - format: uuid + type: string + - maxLength: 1089 + type: string + - type: number + - type: boolean + ScalarAnyOf: + anyOf: + - format: uuid + type: string + - maxLength: 1089 + type: string + - type: number + - type: boolean + description: Values of scalar type using anyOf + Array: + default: [] + description: Values of array type + items: + $ref: "#/components/schemas/Scalar" + minItems: 1 + type: array + NewPet: + properties: + id: + format: int64 + type: integer + x-is-unique: true + category_inline_allof: + $ref: "#/components/schemas/NewPet_category_inline_allof" + category_allOf_ref: + allOf: + - $ref: "#/components/schemas/Category" + category_allOf_ref_description: + allOf: + - $ref: "#/components/schemas/Category" + description: | + Adding description to property using allOf + category_allOf_ref_description_readonly: + allOf: + - $ref: "#/components/schemas/Category" + description: | + Adding description to readonly property using allOf + readOnly: true + name: + example: doggie + type: string + photoUrls: + default: [] + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + default: [] + items: + allOf: + - $ref: "#/components/schemas/Tag" + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + PropertyNameCollision: + properties: + _type: + type: string + type: + type: string + type_: + type: string + type: object + x-internal: false + InteralOnly: + properties: + type: + type: string + type: object + x-internal: true + AllOfModelArrayAnyOf: + allOf: + - $ref: "#/components/schemas/Category" + - properties: + linkListColumn1: + $ref: "#/components/schemas/AllOfModelArrayAnyOf_allOf_linkListColumn1" + attributes: + $ref: "#/components/schemas/AllOfModelArrayAnyOf_allOf_attributes" + type: object + PetUsingAllOf: + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + allOf: + - $ref: "#/components/schemas/Category" + description: | + multi line description + 2nd line + last line + name: + example: doggie + type: string + photoUrls: + default: [] + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + default: [] + items: + allOf: + - $ref: "#/components/schemas/Tag" + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + PetComposition: + allOf: + - $ref: "#/components/schemas/Pet" + PetRef: + properties: + id: + $ref: "#/components/schemas/Pet/properties/id" + category: + $ref: "#/components/schemas/Pet/properties/category" + name: + $ref: "#/components/schemas/Pet/properties/name" + photoUrls: + $ref: "#/components/schemas/Pet/properties/photoUrls" + tags: + $ref: "#/components/schemas/Pet/properties/tags" + status: + $ref: "#/components/schemas/Pet/properties/status" + required: + - name + - photoUrls + type: object + xml: + name: Pet + ArrayOneOf: + oneOf: + - type: integer + - default: [] + items: + type: string + type: array + ArrayAnyOf: + anyOf: + - type: integer + - default: [] + items: + type: string + type: array + ModelWithOneOfAnyOfProperties: + properties: + oneof_prop: + $ref: "#/components/schemas/ArrayOneOf" + anyof_prop: + $ref: "#/components/schemas/ArrayAnyOf" + type: object + NullableEnum: + enum: + - custom + nullable: true + type: string + RequiredNullableBody: + allOf: + - $ref: "#/components/schemas/NullableClass" + - properties: + custom_ref_enum: + $ref: "#/components/schemas/NullableEnum" + custom_enum: + enum: + - custom + nullable: true + type: string + required: + - array_and_items_nullable_prop + - array_items_nullable + - array_nullable_prop + - boolean_prop + - custom_enum + - custom_ref_enum + - date_prop + - datetime_prop + - integer_prop + - number_prop + - object_and_items_nullable_prop + - object_items_nullable + - object_nullable_prop + - string_prop + type: object + example: + integer_prop: 0 + number_prop: 6.027456183070403 + boolean_prop: true + string_prop: string_prop + date_prop: 2000-01-23 + datetime_prop: 2000-01-23T04:56:07.000+00:00 + array_nullable_prop: + - {} + - {} + array_and_items_nullable_prop: + - {} + - {} + array_items_nullable: + - {} + - {} + object_nullable_prop: + key: {} + object_and_items_nullable_prop: + key: {} + object_items_nullable: + key: {} + custom_ref_enum: custom + custom_enum: custom + NestedArrayWithDefaultValues: + properties: + nestedArray: + default: + - - h1 + - Header 1 + - - h2 + - Header 2 + - - h3 + - Header 3 + - - h4 + - Header 4 + items: + default: + - value1 + - value2 + items: + type: string + type: array + type: array + type: object + LongId: + description: Id as long + format: int64 + type: integer + Weight: + description: Weight as float + format: float + type: number + Height: + description: Height as double + format: double + type: number + AllOfRefToLong: + description: Object with allOf ref to long + properties: + id: + allOf: + - $ref: "#/components/schemas/LongId" + default: 10 + type: object + AllOfRefToFloat: + description: Object with allOf ref to float + properties: + weight: + allOf: + - $ref: "#/components/schemas/Weight" + default: 7.89 + type: object + AllOfRefToDouble: + description: Object with allOf ref to double + properties: + height: + allOf: + - $ref: "#/components/schemas/Height" + default: 32.1 + type: object + NullableFieldsValue: + description: Object with required but nullable string fields + example: + before: before + after: after + properties: + before: + nullable: true + type: string + after: + nullable: true + type: string + required: + - after + - before + type: object + NullableFieldsMapSuccess: + additionalProperties: false + description: Success response containing a map of objects with nullable fields + example: + status: status + positions: + key: + before: before + after: after + properties: + status: + type: string + positions: + additionalProperties: + $ref: "#/components/schemas/NullableFieldsValue" + type: object + required: + - positions + - status + type: object + NullableFieldsMapError: + additionalProperties: false + description: Error response + properties: + status: + type: string + reason: + type: string + required: + - reason + - status + type: object + NullableFieldsMapResponse: + anyOf: + - $ref: "#/components/schemas/NullableFieldsMapSuccess" + - $ref: "#/components/schemas/NullableFieldsMapError" + _foo_get_default_response: + example: + string: + bar: bar + properties: + string: + $ref: "#/components/schemas/Foo" + type: object + updatePetWithForm_request: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + uploadFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + testEnumParameters_request: + properties: + enum_form_string_array: + default: [] + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + type: object + testEndpointParameters_request: + properties: + integer: + description: None + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: "/[a-z]/i" + type: string + pattern_without_delimiter: + description: None + pattern: "^[A-Z].*" + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + default: 2010-02-01T10:20:10.11111+01:00 + description: None + example: 2020-02-02T20:20:20.22222Z + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + type: object + testJsonFormData_request: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + type: object + _fake_oneOfWIthSameErasure_get_200_response: + oneOf: + - default: [] + items: + type: string + type: array + - default: [] + items: + type: integer + type: array + _fake_anyOfWIthSameErasure_get_200_response: + anyOf: + - default: [] + items: + type: string + type: array + - default: [] + items: + type: integer + type: array + testInlineFreeformAdditionalProperties_request: + additionalProperties: true + properties: + someProperty: + type: string + type: object + uploadFileWithRequiredFile_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile + type: object + fake_ref_parameter_petId_parameter: + oneOf: + - type: string + - type: integer + FreeFormObjectTestClass_properties: + oneOf: + - type: string + - additionalProperties: true + default: [] + type: object + ArrayOfInlineAllOf_array_allof_dog_property_inner: + allOf: + - properties: + breed: + type: string + type: object + - properties: + color: + type: string + type: object + NewPet_category_inline_allof_allOf_category_tag: + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + NewPet_category_inline_allof: + allOf: + - properties: + id: + format: int64 + type: integer + name: + default: default-name + type: string + category_tag: + $ref: "#/components/schemas/NewPet_category_inline_allof_allOf_category_tag" + required: + - name + type: object + AllOfModelArrayAnyOf_allOf_linkListColumn1_value: + anyOf: + - $ref: "#/components/schemas/User" + - $ref: "#/components/schemas/Tag" + AllOfModelArrayAnyOf_allOf_linkListColumn1: + properties: + value: + default: [] + items: + $ref: "#/components/schemas/AllOfModelArrayAnyOf_allOf_linkListColumn1_value" + type: array + required: + - value + type: object + AllOfModelArrayAnyOf_allOf_attributes_C: + oneOf: + - $ref: "#/components/schemas/Pet" + - $ref: "#/components/schemas/Order" + AllOfModelArrayAnyOf_allOf_attributes: + properties: + C: + $ref: "#/components/schemas/AllOfModelArrayAnyOf_allOf_attributes_C" + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey + api_key_query: + in: query + name: api_key_query + type: apiKey + http_basic_test: + scheme: basic + type: http + bearer_test: + bearerFormat: JWT + scheme: bearer + type: http + diff --git a/samples/client/petstore/java/okhttp/build.gradle b/samples/client/petstore/java/okhttp/build.gradle new file mode 100644 index 000000000000..1aac230d5f71 --- /dev/null +++ b/samples/client/petstore/java/okhttp/build.gradle @@ -0,0 +1,60 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' +apply plugin: 'java' +apply plugin: 'maven-publish' + +group = 'org.openapitools' +version = '1.0.0' + +repositories { + mavenCentral() +} +sourceSets { + main.java.srcDirs = ['src/main/java'] +} + + +sourceCompatibility = JavaVersion.VERSION_1_8 +targetCompatibility = JavaVersion.VERSION_1_8 + +publishing { + publications { + maven(MavenPublication) { + artifactId = 'petstore-okhttp' + from components.java + } + } +} + +task execute(type:JavaExec) { + mainClass = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} + +ext { + jakarta_annotation_version = "1.3.5" + okhttp_version = "5.4.0" +} + +dependencies { + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation "com.squareup.okhttp3:okhttp:$okhttp_version" + implementation "com.squareup.okhttp3:logging-interceptor:$okhttp_version" + implementation 'com.google.code.gson:gson:2.10.1' + implementation 'io.gsonfire:gson-fire:1.9.0' + compileOnly "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.10.3' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.10.3' +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} + +test { + useJUnitPlatform() + dependsOn 'cleanTest' + testLogging { + events "passed", "skipped", "failed" + } +} diff --git a/samples/client/petstore/java/okhttp/build.sbt b/samples/client/petstore/java/okhttp/build.sbt new file mode 100644 index 000000000000..3b5f60007538 --- /dev/null +++ b/samples/client/petstore/java/okhttp/build.sbt @@ -0,0 +1,24 @@ +// Keep the bytecode level in sync with the Maven and Gradle builds. +val javaVersion = "1.8" + +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "petstore-okhttp", + version := "1.0.0", + scalaVersion := "2.13.6", + scalacOptions ++= Seq("-feature"), + compile / javacOptions ++= Seq("-Xlint:deprecation", "-source", javaVersion, "-target", javaVersion), + Compile / packageDoc / publishArtifact := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "com.google.code.findbugs" % "jsr305" % "3.0.2", + "com.squareup.okhttp3" % "okhttp-jvm" % "5.4.0", + "com.squareup.okhttp3" % "logging-interceptor" % "5.4.0", + "com.google.code.gson" % "gson" % "2.10.1", + "io.gsonfire" % "gson-fire" % "1.9.0", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5", + "org.junit.jupiter" % "junit-jupiter-api" % "5.10.3" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/okhttp/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp/docs/AdditionalPropertiesClass.md new file mode 100644 index 000000000000..83051d9be44b --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AdditionalPropertiesClass.md @@ -0,0 +1,20 @@ + + +# AdditionalPropertiesClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**mapProperty** | **Map<String, String>** | | [optional] | +|**mapOfMapProperty** | **Map<String, Map<String, String>>** | | [optional] | +|**anytype1** | **Object** | | [optional] | +|**mapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] | +|**mapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] | +|**mapWithUndeclaredPropertiesAnytype3** | **Map<String, Object>** | | [optional] | +|**emptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] | +|**mapWithUndeclaredPropertiesString** | **Map<String, String>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOf.md b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOf.md new file mode 100644 index 000000000000..96dc5a34d089 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOf.md @@ -0,0 +1,16 @@ + + +# AllOfModelArrayAnyOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | +|**linkListColumn1** | [**AllOfModelArrayAnyOfAllOfLinkListColumn1**](AllOfModelArrayAnyOfAllOfLinkListColumn1.md) | | [optional] | +|**attributes** | [**AllOfModelArrayAnyOfAllOfAttributes**](AllOfModelArrayAnyOfAllOfAttributes.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfAttributes.md b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfAttributes.md new file mode 100644 index 000000000000..c9096e515367 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfAttributes.md @@ -0,0 +1,13 @@ + + +# AllOfModelArrayAnyOfAllOfAttributes + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**C** | [**AllOfModelArrayAnyOfAllOfAttributesC**](AllOfModelArrayAnyOfAllOfAttributesC.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfAttributesC.md b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfAttributesC.md new file mode 100644 index 000000000000..5229de89b299 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfAttributesC.md @@ -0,0 +1,32 @@ + + +# AllOfModelArrayAnyOfAllOfAttributesC + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] | +|**petId** | **Long** | | [optional] | +|**quantity** | **Integer** | | [optional] | +|**shipDate** | **OffsetDateTime** | | [optional] | +|**complete** | **Boolean** | | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| PLACED | "placed" | +| APPROVED | "approved" | +| DELIVERED | "delivered" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md new file mode 100644 index 000000000000..43fa9b696377 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md @@ -0,0 +1,13 @@ + + +# AllOfModelArrayAnyOfAllOfLinkListColumn1 + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**value** | [**List<AllOfModelArrayAnyOfAllOfLinkListColumn1Value>**](AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md) | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md new file mode 100644 index 000000000000..6379cac28b02 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md @@ -0,0 +1,25 @@ + + +# AllOfModelArrayAnyOfAllOfLinkListColumn1Value + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**username** | **String** | | [optional] | +|**firstName** | **String** | | [optional] | +|**lastName** | **String** | | [optional] | +|**email** | **String** | | [optional] | +|**password** | **String** | | [optional] | +|**phone** | **String** | | [optional] | +|**userStatus** | **Integer** | User Status | [optional] | +|**objectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] | +|**objectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] | +|**anyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] | +|**anyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfRefToDouble.md b/samples/client/petstore/java/okhttp/docs/AllOfRefToDouble.md new file mode 100644 index 000000000000..516584f74348 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfRefToDouble.md @@ -0,0 +1,14 @@ + + +# AllOfRefToDouble + +Object with allOf ref to double + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**height** | **Double** | Height as double | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfRefToFloat.md b/samples/client/petstore/java/okhttp/docs/AllOfRefToFloat.md new file mode 100644 index 000000000000..9a60af8a2ea4 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfRefToFloat.md @@ -0,0 +1,14 @@ + + +# AllOfRefToFloat + +Object with allOf ref to float + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**weight** | **Float** | Weight as float | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AllOfRefToLong.md b/samples/client/petstore/java/okhttp/docs/AllOfRefToLong.md new file mode 100644 index 000000000000..0f32d49b0857 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AllOfRefToLong.md @@ -0,0 +1,14 @@ + + +# AllOfRefToLong + +Object with allOf ref to long + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | Id as long | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Animal.md b/samples/client/petstore/java/okhttp/docs/Animal.md new file mode 100644 index 000000000000..d9b32f14c88a --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Animal.md @@ -0,0 +1,14 @@ + + +# Animal + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**className** | **String** | | | +|**color** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AnotherFakeApi.md b/samples/client/petstore/java/okhttp/docs/AnotherFakeApi.md new file mode 100644 index 000000000000..cf5cc7b148a1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AnotherFakeApi.md @@ -0,0 +1,191 @@ +# AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags | +| [**getParameterArrayNumber**](AnotherFakeApi.md#getParameterArrayNumber) | **GET** /fake/parameter-array-number | parameter array number default value | +| [**getParameterStringNumber**](AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number | + + + +# **call123testSpecialTags** +> Client call123testSpecialTags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.call123testSpecialTags(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **getParameterArrayNumber** +> getParameterArrayNumber(array) + +parameter array number default value + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + List array = Arrays.asList(); // List | array integer + try { + apiInstance.getParameterArrayNumber(array); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#getParameterArrayNumber"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **array** | [**List<Integer>**](Integer.md)| array integer | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + + +# **getParameterStringNumber** +> getParameterStringNumber(stringNumber) + +parameter string number + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + BigDecimal stringNumber = new BigDecimal(78); // BigDecimal | string number + try { + apiInstance.getParameterStringNumber(stringNumber); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#getParameterStringNumber"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **stringNumber** | **BigDecimal**| string number | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + diff --git a/samples/client/petstore/java/okhttp/docs/Apple.md b/samples/client/petstore/java/okhttp/docs/Apple.md new file mode 100644 index 000000000000..0ef7a92c74d6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Apple.md @@ -0,0 +1,14 @@ + + +# Apple + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**cultivar** | **String** | | [optional] | +|**origin** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/AppleReq.md b/samples/client/petstore/java/okhttp/docs/AppleReq.md new file mode 100644 index 000000000000..989e1cfedd1e --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/AppleReq.md @@ -0,0 +1,14 @@ + + +# AppleReq + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**cultivar** | **String** | | | +|**mealy** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayAnyOf.md b/samples/client/petstore/java/okhttp/docs/ArrayAnyOf.md new file mode 100644 index 000000000000..86bb944833ac --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayAnyOf.md @@ -0,0 +1,12 @@ + + +# ArrayAnyOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayDefault.md b/samples/client/petstore/java/okhttp/docs/ArrayDefault.md new file mode 100644 index 000000000000..b539cb294d74 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayDefault.md @@ -0,0 +1,14 @@ + + +# ArrayDefault + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**withDefaultEmptyBracket** | **List<String>** | | [optional] | +|**withoutDefault** | **List<String>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 000000000000..0188db3eb131 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfArrayOfNumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayArrayNumber** | **List<List<BigDecimal>>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayOfInlineAllOf.md b/samples/client/petstore/java/okhttp/docs/ArrayOfInlineAllOf.md new file mode 100644 index 000000000000..3efa4933a3b9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayOfInlineAllOf.md @@ -0,0 +1,15 @@ + + +# ArrayOfInlineAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | +|**arrayAllofDogProperty** | [**List<ArrayOfInlineAllOfArrayAllofDogPropertyInner>**](ArrayOfInlineAllOfArrayAllofDogPropertyInner.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInner.md b/samples/client/petstore/java/okhttp/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInner.md new file mode 100644 index 000000000000..35f349597734 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayOfInlineAllOfArrayAllofDogPropertyInner.md @@ -0,0 +1,14 @@ + + +# ArrayOfInlineAllOfArrayAllofDogPropertyInner + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**breed** | **String** | | [optional] | +|**color** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp/docs/ArrayOfNumberOnly.md new file mode 100644 index 000000000000..a5753530aada --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfNumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayNumber** | **List<BigDecimal>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayOneOf.md b/samples/client/petstore/java/okhttp/docs/ArrayOneOf.md new file mode 100644 index 000000000000..34727d5f7301 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayOneOf.md @@ -0,0 +1,12 @@ + + +# ArrayOneOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/ArrayTest.md b/samples/client/petstore/java/okhttp/docs/ArrayTest.md new file mode 100644 index 000000000000..36077c9df300 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ArrayTest.md @@ -0,0 +1,15 @@ + + +# ArrayTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayOfString** | **List<String>** | | [optional] | +|**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] | +|**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Banana.md b/samples/client/petstore/java/okhttp/docs/Banana.md new file mode 100644 index 000000000000..5356d17ee700 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Banana.md @@ -0,0 +1,13 @@ + + +# Banana + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**lengthCm** | **BigDecimal** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/BananaReq.md b/samples/client/petstore/java/okhttp/docs/BananaReq.md new file mode 100644 index 000000000000..22ebe1a7105f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/BananaReq.md @@ -0,0 +1,14 @@ + + +# BananaReq + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**lengthCm** | **BigDecimal** | | | +|**sweet** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/BasquePig.md b/samples/client/petstore/java/okhttp/docs/BasquePig.md new file mode 100644 index 000000000000..160cb71c321f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/BasquePig.md @@ -0,0 +1,13 @@ + + +# BasquePig + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**className** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Capitalization.md b/samples/client/petstore/java/okhttp/docs/Capitalization.md new file mode 100644 index 000000000000..82a812711de2 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Capitalization.md @@ -0,0 +1,18 @@ + + +# Capitalization + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**smallCamel** | **String** | | [optional] | +|**capitalCamel** | **String** | | [optional] | +|**smallSnake** | **String** | | [optional] | +|**capitalSnake** | **String** | | [optional] | +|**scAETHFlowPoints** | **String** | | [optional] | +|**ATT_NAME** | **String** | Name of the pet | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Cat.md b/samples/client/petstore/java/okhttp/docs/Cat.md new file mode 100644 index 000000000000..390dd519c8ce --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Cat.md @@ -0,0 +1,13 @@ + + +# Cat + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**declawed** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Category.md b/samples/client/petstore/java/okhttp/docs/Category.md new file mode 100644 index 000000000000..ab6d1ec334dc --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Category.md @@ -0,0 +1,14 @@ + + +# Category + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ClassModel.md b/samples/client/petstore/java/okhttp/docs/ClassModel.md new file mode 100644 index 000000000000..af46dea1f6c8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ClassModel.md @@ -0,0 +1,14 @@ + + +# ClassModel + +Model for testing model with \"_class\" property + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**propertyClass** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Client.md b/samples/client/petstore/java/okhttp/docs/Client.md new file mode 100644 index 000000000000..ef07b4ab8b9d --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Client.md @@ -0,0 +1,13 @@ + + +# Client + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**client** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ComplexQuadrilateral.md b/samples/client/petstore/java/okhttp/docs/ComplexQuadrilateral.md new file mode 100644 index 000000000000..d0a4b1a0a758 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ComplexQuadrilateral.md @@ -0,0 +1,14 @@ + + +# ComplexQuadrilateral + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**quadrilateralType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/DanishPig.md b/samples/client/petstore/java/okhttp/docs/DanishPig.md new file mode 100644 index 000000000000..0b366d3cf2ff --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/DanishPig.md @@ -0,0 +1,13 @@ + + +# DanishPig + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**className** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/DefaultApi.md b/samples/client/petstore/java/okhttp/docs/DefaultApi.md new file mode 100644 index 000000000000..bfa8273d0c6b --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/DefaultApi.md @@ -0,0 +1,245 @@ +# DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**fakeAnyOfWIthSameErasureGet**](DefaultApi.md#fakeAnyOfWIthSameErasureGet) | **GET** /fake/anyOfWIthSameErasure | | +| [**fakeFreeFormQueryParametersGet**](DefaultApi.md#fakeFreeFormQueryParametersGet) | **GET** /fake/free-form-query-parameters | | +| [**fakeOneOfWIthSameErasureGet**](DefaultApi.md#fakeOneOfWIthSameErasureGet) | **GET** /fake/oneOfWIthSameErasure | | +| [**fooGet**](DefaultApi.md#fooGet) | **GET** /foo | | + + + +# **fakeAnyOfWIthSameErasureGet** +> FakeAnyOfWIthSameErasureGet200Response fakeAnyOfWIthSameErasureGet() + + + +Test route, this shouldn't cause a compiler error + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + FakeAnyOfWIthSameErasureGet200Response result = apiInstance.fakeAnyOfWIthSameErasureGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#fakeAnyOfWIthSameErasureGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**FakeAnyOfWIthSameErasureGet200Response**](FakeAnyOfWIthSameErasureGet200Response.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful response | - | + + +# **fakeFreeFormQueryParametersGet** +> fakeFreeFormQueryParametersGet(fixed, freeForm) + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + String fixed = "fixed_example"; // String | + Object freeForm = null; // Object | + try { + apiInstance.fakeFreeFormQueryParametersGet(fixed, freeForm); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#fakeFreeFormQueryParametersGet"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **fixed** | **String**| | [optional] | +| **freeForm** | [**Object**](.md)| | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + + +# **fakeOneOfWIthSameErasureGet** +> FakeOneOfWIthSameErasureGet200Response fakeOneOfWIthSameErasureGet() + + + +Test route, this shouldn't cause a compiler error + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + FakeOneOfWIthSameErasureGet200Response result = apiInstance.fakeOneOfWIthSameErasureGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#fakeOneOfWIthSameErasureGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**FakeOneOfWIthSameErasureGet200Response**](FakeOneOfWIthSameErasureGet200Response.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful response | - | + + +# **fooGet** +> FooGetDefaultResponse fooGet() + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + FooGetDefaultResponse result = apiInstance.fooGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#fooGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**FooGetDefaultResponse**](FooGetDefaultResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | response | - | + diff --git a/samples/client/petstore/java/okhttp/docs/DeprecatedObject.md b/samples/client/petstore/java/okhttp/docs/DeprecatedObject.md new file mode 100644 index 000000000000..48de1d624425 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/DeprecatedObject.md @@ -0,0 +1,13 @@ + + +# DeprecatedObject + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Dog.md b/samples/client/petstore/java/okhttp/docs/Dog.md new file mode 100644 index 000000000000..972c981c0d05 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Dog.md @@ -0,0 +1,13 @@ + + +# Dog + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**breed** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Drawing.md b/samples/client/petstore/java/okhttp/docs/Drawing.md new file mode 100644 index 000000000000..6b815fc4131b --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Drawing.md @@ -0,0 +1,16 @@ + + +# Drawing + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**mainShape** | [**Shape**](Shape.md) | | [optional] | +|**shapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] | +|**nullableShape** | [**NullableShape**](NullableShape.md) | | [optional] | +|**shapes** | [**List<Shape>**](Shape.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/EnumArrays.md b/samples/client/petstore/java/okhttp/docs/EnumArrays.md new file mode 100644 index 000000000000..b2222d5beb25 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/EnumArrays.md @@ -0,0 +1,32 @@ + + +# EnumArrays + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] | +|**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] | + + + +## Enum: JustSymbolEnum + +| Name | Value | +|---- | -----| +| GREATER_THAN_OR_EQUAL_TO | ">=" | +| DOLLAR | "$" | + + + +## Enum: List<ArrayEnumEnum> + +| Name | Value | +|---- | -----| +| FISH | "fish" | +| CRAB | "crab" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/EnumClass.md b/samples/client/petstore/java/okhttp/docs/EnumClass.md new file mode 100644 index 000000000000..b314590a7591 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/EnumClass.md @@ -0,0 +1,15 @@ + + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/okhttp/docs/EnumStringDiscriminator.md b/samples/client/petstore/java/okhttp/docs/EnumStringDiscriminator.md new file mode 100644 index 000000000000..83aebcdb4226 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/EnumStringDiscriminator.md @@ -0,0 +1,23 @@ + + +# EnumStringDiscriminator + +An object to test discriminator of enum string + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**enumStrType** | [**EnumStrTypeEnum**](#EnumStrTypeEnum) | enum string type | | + + + +## Enum: EnumStrTypeEnum + +| Name | Value | +|---- | -----| +| A | "type_a" | +| B | "type_b" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/EnumTest.md b/samples/client/petstore/java/okhttp/docs/EnumTest.md new file mode 100644 index 000000000000..3e226e18b50b --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/EnumTest.md @@ -0,0 +1,68 @@ + + +# EnumTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] | +|**enumStringRequired** | [**EnumStringRequiredEnum**](#EnumStringRequiredEnum) | | | +|**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] | +|**enumIntegerOnly** | [**EnumIntegerOnlyEnum**](#EnumIntegerOnlyEnum) | | [optional] | +|**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] | +|**outerEnum** | **OuterEnum** | | [optional] | +|**outerEnumInteger** | **OuterEnumInteger** | | [optional] | +|**outerEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] | +|**outerEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] | + + + +## Enum: EnumStringEnum + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | +| EMPTY | "" | + + + +## Enum: EnumStringRequiredEnum + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | +| EMPTY | "" | + + + +## Enum: EnumIntegerEnum + +| Name | Value | +|---- | -----| +| NUMBER_1 | 1 | +| NUMBER_MINUS_1 | -1 | + + + +## Enum: EnumIntegerOnlyEnum + +| Name | Value | +|---- | -----| +| NUMBER_2 | 2 | +| NUMBER_MINUS_2 | -2 | + + + +## Enum: EnumNumberEnum + +| Name | Value | +|---- | -----| +| NUMBER_1_DOT_1 | 1.1 | +| NUMBER_MINUS_1_DOT_2 | -1.2 | + + + diff --git a/samples/client/petstore/java/okhttp/docs/EquilateralTriangle.md b/samples/client/petstore/java/okhttp/docs/EquilateralTriangle.md new file mode 100644 index 000000000000..eade817feb3e --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/EquilateralTriangle.md @@ -0,0 +1,14 @@ + + +# EquilateralTriangle + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**triangleType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/FakeAnyOfWIthSameErasureGet200Response.md b/samples/client/petstore/java/okhttp/docs/FakeAnyOfWIthSameErasureGet200Response.md new file mode 100644 index 000000000000..c224eb3d572f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FakeAnyOfWIthSameErasureGet200Response.md @@ -0,0 +1,12 @@ + + +# FakeAnyOfWIthSameErasureGet200Response + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/FakeApi.md b/samples/client/petstore/java/okhttp/docs/FakeApi.md new file mode 100644 index 000000000000..76a5677e164a --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FakeApi.md @@ -0,0 +1,1571 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**fakeGetFreeFormObjectGet**](FakeApi.md#fakeGetFreeFormObjectGet) | **GET** /fake/get-free-form-object | | +| [**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | | +| [**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | | +| [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | +| [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | +| [**fakeRefParameter**](FakeApi.md#fakeRefParameter) | **POST** /fake/pet/{petId}/reference/parameter | fake reference parameter | +| [**fakeRequiredNullableBodyGet**](FakeApi.md#fakeRequiredNullableBodyGet) | **GET** /fake/required-nullable-body | fields in the response body, required and nullable are both true | +| [**fakeUploadRefRequestBodies**](FakeApi.md#fakeUploadRefRequestBodies) | **POST** /fake/pet/{petId}/uploadImage | fake reference parameter | +| [**getFakeArrayofenums**](FakeApi.md#getFakeArrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**getFakeHealth**](FakeApi.md#getFakeHealth) | **GET** /fake/health | Health check endpoint | +| [**getParameterNameMapping**](FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | +| [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | +| [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | +| [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | +| [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 | +| [**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters | +| [**testGroupParameters**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) | +| [**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties | +| [**testInlineFreeformAdditionalProperties**](FakeApi.md#testInlineFreeformAdditionalProperties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties | +| [**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data | +| [**testNullableRequiredFieldsAnyOf**](FakeApi.md#testNullableRequiredFieldsAnyOf) | **GET** /fake/nullable-required-fields-anyof | test anyOf with map of objects containing nullable required fields | +| [**testQueryParameterCollectionFormat**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | | +| [**testStringMapReference**](FakeApi.md#testStringMapReference) | **POST** /fake/stringMap-reference | test referenced string map | + + + +# **fakeGetFreeFormObjectGet** +> FreeFormObjectTestClass fakeGetFreeFormObjectGet() + + + +Get a free form object or Json string + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + FreeFormObjectTestClass result = apiInstance.fakeGetFreeFormObjectGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeGetFreeFormObjectGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**FreeFormObjectTestClass**](FreeFormObjectTestClass.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +# **fakeOuterBooleanSerialize** +> Boolean fakeOuterBooleanSerialize(body) + + + +Test serialization of outer boolean types + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Boolean body = true; // Boolean | Input boolean as post body + try { + Boolean result = apiInstance.fakeOuterBooleanSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **body** | **Boolean**| Input boolean as post body | [optional] | + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output boolean | - | + + +# **fakeOuterCompositeSerialize** +> OuterComposite fakeOuterCompositeSerialize(outerComposite) + + + +Test serialization of object with outer number type + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + OuterComposite outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body + try { + OuterComposite result = apiInstance.fakeOuterCompositeSerialize(outerComposite); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterCompositeSerialize"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] | + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output composite | - | + + +# **fakeOuterNumberSerialize** +> BigDecimal fakeOuterNumberSerialize(body) + + + +Test serialization of outer number types + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + BigDecimal body = new BigDecimal(78); // BigDecimal | Input number as post body + try { + BigDecimal result = apiInstance.fakeOuterNumberSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterNumberSerialize"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **body** | **BigDecimal**| Input number as post body | [optional] | + +### Return type + +[**BigDecimal**](BigDecimal.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output number | - | + + +# **fakeOuterStringSerialize** +> String fakeOuterStringSerialize(body) + + + +Test serialization of outer string types + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String body = "body_example"; // String | Input string as post body + try { + String result = apiInstance.fakeOuterStringSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterStringSerialize"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **body** | **String**| Input string as post body | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Output string | - | + + +# **fakeRefParameter** +> fakeRefParameter(petId) + +fake reference parameter + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + FakeRefParameterPetIdParameter petId = new FakeRefParameterPetIdParameter(); // FakeRefParameterPetIdParameter | to test oneOf in parameter $ref + try { + apiInstance.fakeRefParameter(petId); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeRefParameter"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | [**FakeRefParameterPetIdParameter**](FakeRefParameterPetIdParameter.md)| to test oneOf in parameter $ref | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **fakeRequiredNullableBodyGet** +> RequiredNullableBody fakeRequiredNullableBodyGet() + +fields in the response body, required and nullable are both true + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + RequiredNullableBody result = apiInstance.fakeRequiredNullableBodyGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeRequiredNullableBodyGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**RequiredNullableBody**](RequiredNullableBody.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | success | - | + + +# **fakeUploadRefRequestBodies** +> ModelApiResponse fakeUploadRefRequestBodies(petId, additionalMetadata, _file) + +fake reference parameter + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File _file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.fakeUploadRefRequestBodies(petId, additionalMetadata, _file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeUploadRefRequestBodies"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | +| **_file** | **File**| file to upload | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **getFakeArrayofenums** +> List<OuterEnum> getFakeArrayofenums() + +Array of Enums + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + List result = apiInstance.getFakeArrayofenums(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#getFakeArrayofenums"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**List<OuterEnum>**](OuterEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Got named array of enums | - | + + +# **getFakeHealth** +> HealthCheckResult getFakeHealth() + +Health check endpoint + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + HealthCheckResult result = apiInstance.getFakeHealth(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#getFakeHealth"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | The instance started successfully | - | + + +# **getParameterNameMapping** +> getParameterNameMapping(underscoreType, type, typeWithUnderscore) + +parameter name mapping test + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Long underscoreType = 56L; // Long | _type + String type = "type_example"; // String | type + String typeWithUnderscore = "typeWithUnderscore_example"; // String | type_ + try { + apiInstance.getParameterNameMapping(underscoreType, type, typeWithUnderscore); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#getParameterNameMapping"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **underscoreType** | **Long**| _type | | +| **type** | **String**| type | | +| **typeWithUnderscore** | **String**| type_ | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + + +# **testAdditionalPropertiesReference** +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **testBodyWithFileSchema** +> testBodyWithFileSchema(fileSchemaTestClass) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + FileSchemaTestClass fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | + try { + apiInstance.testBodyWithFileSchema(fileSchemaTestClass); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithFileSchema"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +# **testBodyWithQueryParams** +> testBodyWithQueryParams(query, user) + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String query = "query_example"; // String | + User user = new User(); // User | + try { + apiInstance.testBodyWithQueryParams(query, user); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithQueryParams"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **query** | **String**| | | +| **user** | [**User**](User.md)| | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +# **testClientModel** +> Client testClientModel(client) + +To test \"client\" model + +To test \"client\" model + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.testClientModel(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testClientModel"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure HTTP basic authorization: http_basic_test + HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); + http_basic_test.setUsername("YOUR USERNAME"); + http_basic_test.setPassword("YOUR PASSWORD"); + + FakeApi apiInstance = new FakeApi(defaultClient); + BigDecimal number = new BigDecimal(78); // BigDecimal | None + Double _double = 3.4D; // Double | None + String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None + byte[] _byte = null; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 56L; // Long | None + Float _float = 3.4F; // Float | None + String string = "string_example"; // String | None + File binary = new File("/path/to/file"); // File | None + LocalDate date = LocalDate.now(); // LocalDate | None + OffsetDateTime dateTime = OffsetDateTime.parse("2010-02-01T10:20:10.111110+01:00"); // OffsetDateTime | None + String password = "password_example"; // String | None + String paramCallback = "paramCallback_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **number** | **BigDecimal**| None | | +| **_double** | **Double**| None | | +| **patternWithoutDelimiter** | **String**| None | | +| **_byte** | **byte[]**| None | | +| **integer** | **Integer**| None | [optional] | +| **int32** | **Integer**| None | [optional] | +| **int64** | **Long**| None | [optional] | +| **_float** | **Float**| None | [optional] | +| **string** | **String**| None | [optional] | +| **binary** | **File**| None | [optional] | +| **date** | **LocalDate**| None | [optional] | +| **dateTime** | **OffsetDateTime**| None | [optional] [default to 2010-02-01T10:20:10.111110+01:00] | +| **password** | **String**| None | [optional] | +| **paramCallback** | **String**| None | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +# **testEnumParameters** +> testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString) + +To test enum parameters + +To test enum parameters + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + List enumHeaderStringArray = Arrays.asList("$"); // List | Header parameter enum test (string array) + String enumHeaderString = "_abc"; // String | Header parameter enum test (string) + List enumQueryStringArray = Arrays.asList("$"); // List | Query parameter enum test (string array) + String enumQueryString = "_abc"; // String | Query parameter enum test (string) + Integer enumQueryInteger = 1; // Integer | Query parameter enum test (double) + Double enumQueryDouble = 1.1D; // Double | Query parameter enum test (double) + List enumFormStringArray = Arrays.asList("$"); // List | Form parameter enum test (string array) + String enumFormString = "_abc"; // String | Form parameter enum test (string) + try { + apiInstance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumParameters"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] | +| **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | +| **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] | +| **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | +| **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] | +| **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] | +| **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] | +| **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid request | - | +| **404** | Not found | - | + + +# **testGroupParameters** +> testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group).stringGroup(stringGroup).booleanGroup(booleanGroup).int64Group(int64Group).execute(); + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure HTTP bearer authorization: bearer_test + HttpBearerAuth bearer_test = (HttpBearerAuth) defaultClient.getAuthentication("bearer_test"); + bearer_test.setBearerToken("BEARER TOKEN"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Integer requiredStringGroup = 56; // Integer | Required String in group parameters + Boolean requiredBooleanGroup = true; // Boolean | Required Boolean in group parameters + Long requiredInt64Group = 56L; // Long | Required Integer in group parameters + Integer stringGroup = 56; // Integer | String in group parameters + Boolean booleanGroup = true; // Boolean | Boolean in group parameters + Long int64Group = 56L; // Long | Integer in group parameters + try { + apiInstance.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) + .stringGroup(stringGroup) + .booleanGroup(booleanGroup) + .int64Group(int64Group) + .execute(); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testGroupParameters"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **requiredStringGroup** | **Integer**| Required String in group parameters | | +| **requiredBooleanGroup** | **Boolean**| Required Boolean in group parameters | | +| **requiredInt64Group** | **Long**| Required Integer in group parameters | | +| **stringGroup** | **Integer**| String in group parameters | [optional] | +| **booleanGroup** | **Boolean**| Boolean in group parameters | [optional] | +| **int64Group** | **Long**| Integer in group parameters | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Something wrong | - | + + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(requestBody) + +test inline additionalProperties + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = new HashMap(); // Map | request body + try { + apiInstance.testInlineAdditionalProperties(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, String>**](String.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **testInlineFreeformAdditionalProperties** +> testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest) + +test inline free-form additionalProperties + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = new TestInlineFreeformAdditionalPropertiesRequest(); // TestInlineFreeformAdditionalPropertiesRequest | request body + try { + apiInstance.testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineFreeformAdditionalProperties"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **testInlineFreeformAdditionalPropertiesRequest** | [**TestInlineFreeformAdditionalPropertiesRequest**](TestInlineFreeformAdditionalPropertiesRequest.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **testJsonFormData** +> testJsonFormData(param, param2) + +test json serialization of form data + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String param = "param_example"; // String | field1 + String param2 = "param2_example"; // String | field2 + try { + apiInstance.testJsonFormData(param, param2); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testJsonFormData"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **param** | **String**| field1 | | +| **param2** | **String**| field2 | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **testNullableRequiredFieldsAnyOf** +> NullableFieldsMapResponse testNullableRequiredFieldsAnyOf() + +test anyOf with map of objects containing nullable required fields + +Tests that anyOf deserialization works when object values contain required fields that are nullable (e.g. Record<string, { before: string | null, after: string | null }>) + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + NullableFieldsMapResponse result = apiInstance.testNullableRequiredFieldsAnyOf(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testNullableRequiredFieldsAnyOf"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**NullableFieldsMapResponse**](NullableFieldsMapResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **testQueryParameterCollectionFormat** +> testQueryParameterCollectionFormat(pipe, ioutil, http, url, context) + + + +To test the collection format in query parameters + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + List pipe = Arrays.asList(); // List | + List ioutil = Arrays.asList(); // List | + List http = Arrays.asList(); // List | + List url = Arrays.asList(); // List | + List context = Arrays.asList(); // List | + try { + apiInstance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testQueryParameterCollectionFormat"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **pipe** | [**List<String>**](String.md)| | | +| **ioutil** | [**List<String>**](String.md)| | | +| **http** | [**List<String>**](String.md)| | | +| **url** | [**List<String>**](String.md)| | | +| **context** | [**List<String>**](String.md)| | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + + +# **testStringMapReference** +> testStringMapReference(requestBody) + +test referenced string map + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = new HashMap(); // Map | request body + try { + apiInstance.testStringMapReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testStringMapReference"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, String>**](String.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java/okhttp/docs/FakeClassnameTags123Api.md b/samples/client/petstore/java/okhttp/docs/FakeClassnameTags123Api.md new file mode 100644 index 000000000000..5abe126078c6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FakeClassnameTags123Api.md @@ -0,0 +1,78 @@ +# FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case | + + + +# **testClassname** +> Client testClassname(client) + +To test class name in snake case + +To test class name in snake case + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeClassnameTags123Api; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + FakeClassnameTags123Api apiInstance = new FakeClassnameTags123Api(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.testClassname(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeClassnameTags123Api#testClassname"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **client** | [**Client**](Client.md)| client model | | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java/okhttp/docs/FakeOneOfWIthSameErasureGet200Response.md b/samples/client/petstore/java/okhttp/docs/FakeOneOfWIthSameErasureGet200Response.md new file mode 100644 index 000000000000..0a3fbf6f8fca --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FakeOneOfWIthSameErasureGet200Response.md @@ -0,0 +1,12 @@ + + +# FakeOneOfWIthSameErasureGet200Response + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/FakeRefParameterPetIdParameter.md b/samples/client/petstore/java/okhttp/docs/FakeRefParameterPetIdParameter.md new file mode 100644 index 000000000000..1328d3c125c4 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FakeRefParameterPetIdParameter.md @@ -0,0 +1,12 @@ + + +# FakeRefParameterPetIdParameter + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/FileSchemaTestClass.md b/samples/client/petstore/java/okhttp/docs/FileSchemaTestClass.md new file mode 100644 index 000000000000..85d1a0636694 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FileSchemaTestClass.md @@ -0,0 +1,14 @@ + + +# FileSchemaTestClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_file** | [**ModelFile**](ModelFile.md) | | [optional] | +|**files** | [**List<ModelFile>**](ModelFile.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Foo.md b/samples/client/petstore/java/okhttp/docs/Foo.md new file mode 100644 index 000000000000..6b3f0556528a --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Foo.md @@ -0,0 +1,13 @@ + + +# Foo + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/FooGetDefaultResponse.md b/samples/client/petstore/java/okhttp/docs/FooGetDefaultResponse.md new file mode 100644 index 000000000000..ff3d7a3a56c3 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FooGetDefaultResponse.md @@ -0,0 +1,13 @@ + + +# FooGetDefaultResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**string** | [**Foo**](Foo.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/FormatTest.md b/samples/client/petstore/java/okhttp/docs/FormatTest.md new file mode 100644 index 000000000000..71790022c16d --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FormatTest.md @@ -0,0 +1,29 @@ + + +# FormatTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**integer** | **Integer** | | [optional] | +|**int32** | **Integer** | | [optional] | +|**int64** | **Long** | | [optional] | +|**number** | **BigDecimal** | | | +|**_float** | **Float** | | [optional] | +|**_double** | **Double** | | [optional] | +|**decimal** | **BigDecimal** | | [optional] | +|**string** | **String** | | [optional] | +|**_byte** | **byte[]** | | | +|**binary** | **File** | | [optional] | +|**date** | **LocalDate** | | | +|**dateTime** | **OffsetDateTime** | | [optional] | +|**uuid** | **UUID** | | [optional] | +|**uuidWithDefault** | **UUID** | | [optional] | +|**password** | **String** | | | +|**patternWithDigits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] | +|**patternWithDigitsAndDelimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/FreeFormObjectTestClass.md b/samples/client/petstore/java/okhttp/docs/FreeFormObjectTestClass.md new file mode 100644 index 000000000000..3bb6144bc90b --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FreeFormObjectTestClass.md @@ -0,0 +1,14 @@ + + +# FreeFormObjectTestClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **String** | | [optional] | +|**properties** | [**FreeFormObjectTestClassProperties**](FreeFormObjectTestClassProperties.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/FreeFormObjectTestClassProperties.md b/samples/client/petstore/java/okhttp/docs/FreeFormObjectTestClassProperties.md new file mode 100644 index 000000000000..8a7c9d2838a3 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FreeFormObjectTestClassProperties.md @@ -0,0 +1,12 @@ + + +# FreeFormObjectTestClassProperties + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/Fruit.md b/samples/client/petstore/java/okhttp/docs/Fruit.md new file mode 100644 index 000000000000..f1915ef9b5b6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Fruit.md @@ -0,0 +1,16 @@ + + +# Fruit + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**color** | **String** | | [optional] | +|**cultivar** | **String** | | [optional] | +|**origin** | **String** | | [optional] | +|**lengthCm** | **BigDecimal** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/FruitReq.md b/samples/client/petstore/java/okhttp/docs/FruitReq.md new file mode 100644 index 000000000000..859a881b53ec --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/FruitReq.md @@ -0,0 +1,16 @@ + + +# FruitReq + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**cultivar** | **String** | | | +|**mealy** | **Boolean** | | [optional] | +|**lengthCm** | **BigDecimal** | | | +|**sweet** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/GmFruit.md b/samples/client/petstore/java/okhttp/docs/GmFruit.md new file mode 100644 index 000000000000..1a301bf9600a --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/GmFruit.md @@ -0,0 +1,16 @@ + + +# GmFruit + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**color** | **String** | | [optional] | +|**cultivar** | **String** | | [optional] | +|**origin** | **String** | | [optional] | +|**lengthCm** | **BigDecimal** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/GrandparentAnimal.md b/samples/client/petstore/java/okhttp/docs/GrandparentAnimal.md new file mode 100644 index 000000000000..9737408f2724 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/GrandparentAnimal.md @@ -0,0 +1,13 @@ + + +# GrandparentAnimal + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**petType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/okhttp/docs/HasOnlyReadOnly.md new file mode 100644 index 000000000000..29da5205dbba --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/HasOnlyReadOnly.md @@ -0,0 +1,14 @@ + + +# HasOnlyReadOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] [readonly] | +|**foo** | **String** | | [optional] [readonly] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/HealthCheckResult.md b/samples/client/petstore/java/okhttp/docs/HealthCheckResult.md new file mode 100644 index 000000000000..4885e6f1cada --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/HealthCheckResult.md @@ -0,0 +1,14 @@ + + +# HealthCheckResult + +Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**nullableMessage** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/IsoscelesTriangle.md b/samples/client/petstore/java/okhttp/docs/IsoscelesTriangle.md new file mode 100644 index 000000000000..0bd5045bc68f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/IsoscelesTriangle.md @@ -0,0 +1,14 @@ + + +# IsoscelesTriangle + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**triangleType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Mammal.md b/samples/client/petstore/java/okhttp/docs/Mammal.md new file mode 100644 index 000000000000..71f0fce48839 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Mammal.md @@ -0,0 +1,26 @@ + + +# Mammal + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**hasBaleen** | **Boolean** | | [optional] | +|**hasTeeth** | **Boolean** | | [optional] | +|**className** | **String** | | | +|**type** | [**TypeEnum**](#TypeEnum) | | [optional] | + + + +## Enum: TypeEnum + +| Name | Value | +|---- | -----| +| PLAINS | "plains" | +| MOUNTAIN | "mountain" | +| GREVYS | "grevys" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/MammalAnyof.md b/samples/client/petstore/java/okhttp/docs/MammalAnyof.md new file mode 100644 index 000000000000..7a366e10da49 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/MammalAnyof.md @@ -0,0 +1,26 @@ + + +# MammalAnyof + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**hasBaleen** | **Boolean** | | [optional] | +|**hasTeeth** | **Boolean** | | [optional] | +|**className** | **String** | | | +|**type** | [**TypeEnum**](#TypeEnum) | | [optional] | + + + +## Enum: TypeEnum + +| Name | Value | +|---- | -----| +| PLAINS | "plains" | +| MOUNTAIN | "mountain" | +| GREVYS | "grevys" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/MapTest.md b/samples/client/petstore/java/okhttp/docs/MapTest.md new file mode 100644 index 000000000000..54380188e1d6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/MapTest.md @@ -0,0 +1,25 @@ + + +# MapTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**mapMapOfString** | **Map<String, Map<String, String>>** | | [optional] | +|**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] | +|**directMap** | **Map<String, Boolean>** | | [optional] | +|**indirectMap** | **Map<String, Boolean>** | | [optional] | + + + +## Enum: Map<String, InnerEnum> + +| Name | Value | +|---- | -----| +| UPPER | "UPPER" | +| LOWER | "lower" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 000000000000..a5ddf0faa6a9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,15 @@ + + +# MixedPropertiesAndAdditionalPropertiesClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**uuid** | **UUID** | | [optional] | +|**dateTime** | **OffsetDateTime** | | [optional] | +|**map** | [**Map<String, Animal>**](Animal.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Model200Response.md b/samples/client/petstore/java/okhttp/docs/Model200Response.md new file mode 100644 index 000000000000..109411580c62 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Model200Response.md @@ -0,0 +1,15 @@ + + +# Model200Response + +Model for testing model name starting with number + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **Integer** | | [optional] | +|**propertyClass** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ModelApiResponse.md b/samples/client/petstore/java/okhttp/docs/ModelApiResponse.md new file mode 100644 index 000000000000..e374c2dd2dec --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ModelApiResponse.md @@ -0,0 +1,15 @@ + + +# ModelApiResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**code** | **Integer** | | [optional] | +|**type** | **String** | | [optional] | +|**message** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ModelFile.md b/samples/client/petstore/java/okhttp/docs/ModelFile.md new file mode 100644 index 000000000000..adcde984f527 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ModelFile.md @@ -0,0 +1,14 @@ + + +# ModelFile + +Must be named `File` for test. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**sourceURI** | **String** | Test capitalization | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ModelList.md b/samples/client/petstore/java/okhttp/docs/ModelList.md new file mode 100644 index 000000000000..f93ab7dde8d4 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ModelList.md @@ -0,0 +1,13 @@ + + +# ModelList + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_123list** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ModelReturn.md b/samples/client/petstore/java/okhttp/docs/ModelReturn.md new file mode 100644 index 000000000000..0bd356861eb7 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ModelReturn.md @@ -0,0 +1,14 @@ + + +# ModelReturn + +Model for testing reserved words + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**_return** | **Integer** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ModelWithOneOfAnyOfProperties.md b/samples/client/petstore/java/okhttp/docs/ModelWithOneOfAnyOfProperties.md new file mode 100644 index 000000000000..64c1206365fd --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ModelWithOneOfAnyOfProperties.md @@ -0,0 +1,14 @@ + + +# ModelWithOneOfAnyOfProperties + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**oneofProp** | [**ArrayOneOf**](ArrayOneOf.md) | | [optional] | +|**anyofProp** | [**ArrayAnyOf**](ArrayAnyOf.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Name.md b/samples/client/petstore/java/okhttp/docs/Name.md new file mode 100644 index 000000000000..c901d9435309 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Name.md @@ -0,0 +1,17 @@ + + +# Name + +Model for testing model name same as property name + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **Integer** | | | +|**snakeCase** | **Integer** | | [optional] [readonly] | +|**property** | **String** | | [optional] | +|**_123number** | **Integer** | | [optional] [readonly] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NestedArrayWithDefaultValues.md b/samples/client/petstore/java/okhttp/docs/NestedArrayWithDefaultValues.md new file mode 100644 index 000000000000..c5f272f1cb30 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NestedArrayWithDefaultValues.md @@ -0,0 +1,13 @@ + + +# NestedArrayWithDefaultValues + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**nestedArray** | **List<List<String>>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NewPet.md b/samples/client/petstore/java/okhttp/docs/NewPet.md new file mode 100644 index 000000000000..3cfa8c0076fe --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NewPet.md @@ -0,0 +1,31 @@ + + +# NewPet + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**categoryInlineAllof** | [**NewPetCategoryInlineAllof**](NewPetCategoryInlineAllof.md) | | [optional] | +|**categoryAllOfRef** | [**Category**](Category.md) | | [optional] | +|**categoryAllOfRefDescription** | [**Category**](Category.md) | Adding description to property using allOf | [optional] | +|**categoryAllOfRefDescriptionReadonly** | [**Category**](Category.md) | Adding description to readonly property using allOf | [optional] [readonly] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NewPetCategoryInlineAllof.md b/samples/client/petstore/java/okhttp/docs/NewPetCategoryInlineAllof.md new file mode 100644 index 000000000000..7e8872f8132d --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NewPetCategoryInlineAllof.md @@ -0,0 +1,15 @@ + + +# NewPetCategoryInlineAllof + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | +|**categoryTag** | [**NewPetCategoryInlineAllofAllOfCategoryTag**](NewPetCategoryInlineAllofAllOfCategoryTag.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NewPetCategoryInlineAllofAllOfCategoryTag.md b/samples/client/petstore/java/okhttp/docs/NewPetCategoryInlineAllofAllOfCategoryTag.md new file mode 100644 index 000000000000..d685440279e9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NewPetCategoryInlineAllofAllOfCategoryTag.md @@ -0,0 +1,14 @@ + + +# NewPetCategoryInlineAllofAllOfCategoryTag + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NullableClass.md b/samples/client/petstore/java/okhttp/docs/NullableClass.md new file mode 100644 index 000000000000..fa98c5c6d984 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NullableClass.md @@ -0,0 +1,24 @@ + + +# NullableClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**integerProp** | **Integer** | | [optional] | +|**numberProp** | **BigDecimal** | | [optional] | +|**booleanProp** | **Boolean** | | [optional] | +|**stringProp** | **String** | | [optional] | +|**dateProp** | **LocalDate** | | [optional] | +|**datetimeProp** | **OffsetDateTime** | | [optional] | +|**arrayNullableProp** | **List<Object>** | | [optional] | +|**arrayAndItemsNullableProp** | **List<Object>** | | [optional] | +|**arrayItemsNullable** | **List<Object>** | | [optional] | +|**objectNullableProp** | **Map<String, Object>** | | [optional] | +|**objectAndItemsNullableProp** | **Map<String, Object>** | | [optional] | +|**objectItemsNullable** | **Map<String, Object>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NullableEnum.md b/samples/client/petstore/java/okhttp/docs/NullableEnum.md new file mode 100644 index 000000000000..774c8d6b1d70 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NullableEnum.md @@ -0,0 +1,11 @@ + + +# NullableEnum + +## Enum + + +* `CUSTOM` (value: `"custom"`) + + + diff --git a/samples/client/petstore/java/okhttp/docs/NullableFieldsMapError.md b/samples/client/petstore/java/okhttp/docs/NullableFieldsMapError.md new file mode 100644 index 000000000000..c129f355904a --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NullableFieldsMapError.md @@ -0,0 +1,15 @@ + + +# NullableFieldsMapError + +Error response + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**status** | **String** | | | +|**reason** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NullableFieldsMapResponse.md b/samples/client/petstore/java/okhttp/docs/NullableFieldsMapResponse.md new file mode 100644 index 000000000000..de7b03be5807 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NullableFieldsMapResponse.md @@ -0,0 +1,15 @@ + + +# NullableFieldsMapResponse + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**status** | **String** | | | +|**positions** | [**Map<String, NullableFieldsValue>**](NullableFieldsValue.md) | | | +|**reason** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NullableFieldsMapSuccess.md b/samples/client/petstore/java/okhttp/docs/NullableFieldsMapSuccess.md new file mode 100644 index 000000000000..0ce60cd148f9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NullableFieldsMapSuccess.md @@ -0,0 +1,15 @@ + + +# NullableFieldsMapSuccess + +Success response containing a map of objects with nullable fields + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**status** | **String** | | | +|**positions** | [**Map<String, NullableFieldsValue>**](NullableFieldsValue.md) | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NullableFieldsValue.md b/samples/client/petstore/java/okhttp/docs/NullableFieldsValue.md new file mode 100644 index 000000000000..397f73f74007 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NullableFieldsValue.md @@ -0,0 +1,15 @@ + + +# NullableFieldsValue + +Object with required but nullable string fields + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**before** | **String** | | | +|**after** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NullableShape.md b/samples/client/petstore/java/okhttp/docs/NullableShape.md new file mode 100644 index 000000000000..9d40680fd2c2 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NullableShape.md @@ -0,0 +1,16 @@ + + +# NullableShape + +The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**triangleType** | **String** | | | +|**quadrilateralType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/NumberOnly.md b/samples/client/petstore/java/okhttp/docs/NumberOnly.md new file mode 100644 index 000000000000..b8ed1a4cfae1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/NumberOnly.md @@ -0,0 +1,13 @@ + + +# NumberOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**justNumber** | **BigDecimal** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ObjectWithDeprecatedFields.md b/samples/client/petstore/java/okhttp/docs/ObjectWithDeprecatedFields.md new file mode 100644 index 000000000000..f1cf571f4c09 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ObjectWithDeprecatedFields.md @@ -0,0 +1,16 @@ + + +# ObjectWithDeprecatedFields + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**uuid** | **String** | | [optional] | +|**id** | **BigDecimal** | | [optional] | +|**deprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] | +|**bars** | **List<String>** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Order.md b/samples/client/petstore/java/okhttp/docs/Order.md new file mode 100644 index 000000000000..27af32855c5c --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Order.md @@ -0,0 +1,28 @@ + + +# Order + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**petId** | **Long** | | [optional] | +|**quantity** | **Integer** | | [optional] | +|**shipDate** | **OffsetDateTime** | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] | +|**complete** | **Boolean** | | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| PLACED | "placed" | +| APPROVED | "approved" | +| DELIVERED | "delivered" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/OuterComposite.md b/samples/client/petstore/java/okhttp/docs/OuterComposite.md new file mode 100644 index 000000000000..98b56e0763ff --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/OuterComposite.md @@ -0,0 +1,15 @@ + + +# OuterComposite + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**myNumber** | **BigDecimal** | | [optional] | +|**myString** | **String** | | [optional] | +|**myBoolean** | **Boolean** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/OuterEnum.md b/samples/client/petstore/java/okhttp/docs/OuterEnum.md new file mode 100644 index 000000000000..e9228f060d25 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/OuterEnum.md @@ -0,0 +1,19 @@ + + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + +* `LOWER_CASE_S` (value: `"s"`) + +* `UPPER_CASE_S` (value: `"S"`) + + + diff --git a/samples/client/petstore/java/okhttp/docs/OuterEnumDefaultValue.md b/samples/client/petstore/java/okhttp/docs/OuterEnumDefaultValue.md new file mode 100644 index 000000000000..cbc7f4ba54d2 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/OuterEnumDefaultValue.md @@ -0,0 +1,15 @@ + + +# OuterEnumDefaultValue + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/okhttp/docs/OuterEnumInteger.md b/samples/client/petstore/java/okhttp/docs/OuterEnumInteger.md new file mode 100644 index 000000000000..f71dea30ad00 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/OuterEnumInteger.md @@ -0,0 +1,15 @@ + + +# OuterEnumInteger + +## Enum + + +* `NUMBER_0` (value: `0`) + +* `NUMBER_1` (value: `1`) + +* `NUMBER_2` (value: `2`) + + + diff --git a/samples/client/petstore/java/okhttp/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/java/okhttp/docs/OuterEnumIntegerDefaultValue.md new file mode 100644 index 000000000000..99e6389f4278 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,15 @@ + + +# OuterEnumIntegerDefaultValue + +## Enum + + +* `NUMBER_0` (value: `0`) + +* `NUMBER_1` (value: `1`) + +* `NUMBER_2` (value: `2`) + + + diff --git a/samples/client/petstore/java/okhttp/docs/ParentPet.md b/samples/client/petstore/java/okhttp/docs/ParentPet.md new file mode 100644 index 000000000000..4992b88a6710 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ParentPet.md @@ -0,0 +1,12 @@ + + +# ParentPet + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/Pet.md b/samples/client/petstore/java/okhttp/docs/Pet.md new file mode 100644 index 000000000000..08dfd8623602 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Pet.md @@ -0,0 +1,28 @@ + + +# Pet + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/PetApi.md b/samples/client/petstore/java/okhttp/docs/PetApi.md new file mode 100644 index 000000000000..83ca6607deb3 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/PetApi.md @@ -0,0 +1,640 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store | +| [**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID | +| [**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet | +| [**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image | +| [**uploadFileWithRequiredFile**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) | + + + +# **addPet** +> addPet(pet) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(pet); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + apiInstance.deletePet(petId, apiKey); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| Pet id to delete | | +| **apiKey** | **String**| | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List tags = Arrays.asList(); // List | Tags to filter by + try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **tags** | [**List<String>**](String.md)| Tags to filter by | | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +# **updatePet** +> updatePet(pet) + +Update an existing pet + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.updatePet(pet); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + apiInstance.updatePetWithForm(petId, name, status); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet that needs to be updated | | +| **name** | **String**| Updated name of the pet | [optional] | +| **status** | **String**| Updated status of the pet | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, contentType, additionalMetadata, _file) + +uploads an image + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String contentType = "contentType_example"; // String | Content type header parameter + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File _file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId, contentType, additionalMetadata, _file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **contentType** | **String**| Content type header parameter | [optional] | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | +| **_file** | **File**| file to upload | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **uploadFileWithRequiredFile** +> ModelApiResponse uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata) + +uploads an image (required) + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + File requiredFile = new File("/path/to/file"); // File | file to upload + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + try { + ModelApiResponse result = apiInstance.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFileWithRequiredFile"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **requiredFile** | **File**| file to upload | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java/okhttp/docs/PetComposition.md b/samples/client/petstore/java/okhttp/docs/PetComposition.md new file mode 100644 index 000000000000..3f93a8972ddc --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/PetComposition.md @@ -0,0 +1,28 @@ + + +# PetComposition + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/PetRef.md b/samples/client/petstore/java/okhttp/docs/PetRef.md new file mode 100644 index 000000000000..256faf704c49 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/PetRef.md @@ -0,0 +1,28 @@ + + +# PetRef + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/PetUsingAllOf.md b/samples/client/petstore/java/okhttp/docs/PetUsingAllOf.md new file mode 100644 index 000000000000..379da2dc359f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/PetUsingAllOf.md @@ -0,0 +1,28 @@ + + +# PetUsingAllOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | multi line description 2nd line last line | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/PetWithRequiredTags.md b/samples/client/petstore/java/okhttp/docs/PetWithRequiredTags.md new file mode 100644 index 000000000000..2f528f536e99 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/PetWithRequiredTags.md @@ -0,0 +1,28 @@ + + +# PetWithRequiredTags + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Pig.md b/samples/client/petstore/java/okhttp/docs/Pig.md new file mode 100644 index 000000000000..61079c61c498 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Pig.md @@ -0,0 +1,13 @@ + + +# Pig + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**className** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/PropertyNameCollision.md b/samples/client/petstore/java/okhttp/docs/PropertyNameCollision.md new file mode 100644 index 000000000000..28775f9b7481 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/PropertyNameCollision.md @@ -0,0 +1,15 @@ + + +# PropertyNameCollision + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**underscoreType** | **String** | | [optional] | +|**type** | **String** | | [optional] | +|**typeWithUnderscore** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Quadrilateral.md b/samples/client/petstore/java/okhttp/docs/Quadrilateral.md new file mode 100644 index 000000000000..af9f89a6f710 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Quadrilateral.md @@ -0,0 +1,14 @@ + + +# Quadrilateral + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**quadrilateralType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/QuadrilateralInterface.md b/samples/client/petstore/java/okhttp/docs/QuadrilateralInterface.md new file mode 100644 index 000000000000..99451f3bd020 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/QuadrilateralInterface.md @@ -0,0 +1,13 @@ + + +# QuadrilateralInterface + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**quadrilateralType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ReadOnlyFirst.md b/samples/client/petstore/java/okhttp/docs/ReadOnlyFirst.md new file mode 100644 index 000000000000..ad6af7ee155f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ReadOnlyFirst.md @@ -0,0 +1,14 @@ + + +# ReadOnlyFirst + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**bar** | **String** | | [optional] [readonly] | +|**baz** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/RequiredNullableBody.md b/samples/client/petstore/java/okhttp/docs/RequiredNullableBody.md new file mode 100644 index 000000000000..b732ff05be76 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/RequiredNullableBody.md @@ -0,0 +1,34 @@ + + +# RequiredNullableBody + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**integerProp** | **Integer** | | | +|**numberProp** | **BigDecimal** | | | +|**booleanProp** | **Boolean** | | | +|**stringProp** | **String** | | | +|**dateProp** | **LocalDate** | | | +|**datetimeProp** | **OffsetDateTime** | | | +|**arrayNullableProp** | **List<Object>** | | | +|**arrayAndItemsNullableProp** | **List<Object>** | | | +|**arrayItemsNullable** | **List<Object>** | | | +|**objectNullableProp** | **Map<String, Object>** | | | +|**objectAndItemsNullableProp** | **Map<String, Object>** | | | +|**objectItemsNullable** | **Map<String, Object>** | | | +|**customRefEnum** | **NullableEnum** | | | +|**customEnum** | [**CustomEnumEnum**](#CustomEnumEnum) | | | + + + +## Enum: CustomEnumEnum + +| Name | Value | +|---- | -----| +| CUSTOM | "custom" | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Scalar.md b/samples/client/petstore/java/okhttp/docs/Scalar.md new file mode 100644 index 000000000000..45dbf799e91f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Scalar.md @@ -0,0 +1,13 @@ + + +# Scalar + +Values of scalar type + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/ScalarAnyOf.md b/samples/client/petstore/java/okhttp/docs/ScalarAnyOf.md new file mode 100644 index 000000000000..767e9196023d --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ScalarAnyOf.md @@ -0,0 +1,13 @@ + + +# ScalarAnyOf + +Values of scalar type using anyOf + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/ScaleneTriangle.md b/samples/client/petstore/java/okhttp/docs/ScaleneTriangle.md new file mode 100644 index 000000000000..c578f6cbfaab --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ScaleneTriangle.md @@ -0,0 +1,14 @@ + + +# ScaleneTriangle + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**triangleType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Shape.md b/samples/client/petstore/java/okhttp/docs/Shape.md new file mode 100644 index 000000000000..51549d7b67f9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Shape.md @@ -0,0 +1,15 @@ + + +# Shape + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**triangleType** | **String** | | | +|**quadrilateralType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ShapeInterface.md b/samples/client/petstore/java/okhttp/docs/ShapeInterface.md new file mode 100644 index 000000000000..b4f981e3b566 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ShapeInterface.md @@ -0,0 +1,13 @@ + + +# ShapeInterface + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/ShapeOrNull.md b/samples/client/petstore/java/okhttp/docs/ShapeOrNull.md new file mode 100644 index 000000000000..c4ae8f1b6720 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ShapeOrNull.md @@ -0,0 +1,16 @@ + + +# ShapeOrNull + +The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**triangleType** | **String** | | | +|**quadrilateralType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/SimpleQuadrilateral.md b/samples/client/petstore/java/okhttp/docs/SimpleQuadrilateral.md new file mode 100644 index 000000000000..52fb7d1a6a49 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/SimpleQuadrilateral.md @@ -0,0 +1,14 @@ + + +# SimpleQuadrilateral + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**quadrilateralType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/SpecialModelName.md b/samples/client/petstore/java/okhttp/docs/SpecialModelName.md new file mode 100644 index 000000000000..e17d0d797b7f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/SpecialModelName.md @@ -0,0 +1,14 @@ + + +# SpecialModelName + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**$specialPropertyName** | **Long** | | [optional] | +|**specialModelName** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/StoreApi.md b/samples/client/petstore/java/okhttp/docs/StoreApi.md new file mode 100644 index 000000000000..a923bf9da0b6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/StoreApi.md @@ -0,0 +1,266 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID | +| [**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID | +| [**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet | + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + String orderId = "orderId_example"; // String | ID of the order that needs to be deleted + try { + apiInstance.deleteOrder(orderId); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **String**| ID of the order that needs to be deleted | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + StoreApi apiInstance = new StoreApi(defaultClient); + try { + Map result = apiInstance.getInventory(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of pet that needs to be fetched + try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **Long**| ID of pet that needs to be fetched | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +# **placeOrder** +> Order placeOrder(order) + +Place an order for a pet + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Order order = new Order(); // Order | order placed for purchasing the pet + try { + Order result = apiInstance.placeOrder(order); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **order** | [**Order**](Order.md)| order placed for purchasing the pet | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/samples/client/petstore/java/okhttp/docs/Tag.md b/samples/client/petstore/java/okhttp/docs/Tag.md new file mode 100644 index 000000000000..5088b2dd1c31 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Tag.md @@ -0,0 +1,14 @@ + + +# Tag + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md b/samples/client/petstore/java/okhttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md new file mode 100644 index 000000000000..dc066e6c7dac --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -0,0 +1,13 @@ + + +# TestInlineFreeformAdditionalPropertiesRequest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**someProperty** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Triangle.md b/samples/client/petstore/java/okhttp/docs/Triangle.md new file mode 100644 index 000000000000..71de2174f744 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Triangle.md @@ -0,0 +1,14 @@ + + +# Triangle + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**shapeType** | **String** | | | +|**triangleType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/TriangleInterface.md b/samples/client/petstore/java/okhttp/docs/TriangleInterface.md new file mode 100644 index 000000000000..ef5fc7575f34 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/TriangleInterface.md @@ -0,0 +1,13 @@ + + +# TriangleInterface + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**triangleType** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/User.md b/samples/client/petstore/java/okhttp/docs/User.md new file mode 100644 index 000000000000..9e97dc35485f --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/User.md @@ -0,0 +1,24 @@ + + +# User + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**username** | **String** | | [optional] | +|**firstName** | **String** | | [optional] | +|**lastName** | **String** | | [optional] | +|**email** | **String** | | [optional] | +|**password** | **String** | | [optional] | +|**phone** | **String** | | [optional] | +|**userStatus** | **Integer** | User Status | [optional] | +|**objectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] | +|**objectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] | +|**anyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] | +|**anyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp/docs/UserApi.md b/samples/client/petstore/java/okhttp/docs/UserApi.md new file mode 100644 index 000000000000..44f18757d6b6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/UserApi.md @@ -0,0 +1,511 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**createUser**](UserApi.md#createUser) | **POST** /user | Create user | +| [**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user | +| [**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name | +| [**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system | +| [**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session | +| [**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user | + + + +# **createUser** +> createUser(user) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + User user = new User(); // User | Created user object + try { + apiInstance.createUser(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **user** | [**User**](User.md)| Created user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(user) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithArrayInput(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +# **createUsersWithListInput** +> createUsersWithListInput(user) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithListInput(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be deleted + try { + apiInstance.deleteUser(username); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be deleted | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. + try { + User result = apiInstance.getUserByName(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The user name for login + String password = "password_example"; // String | The password for login in clear text + try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The user name for login | | +| **password** | **String**| The password for login in clear text | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
| +| **400** | Invalid username/password supplied | - | + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + try { + apiInstance.logoutUser(); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +# **updateUser** +> updateUser(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | name that need to be deleted + User user = new User(); // User | Updated user object + try { + apiInstance.updateUser(username, user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + 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 | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| name that need to be deleted | | +| **user** | [**User**](User.md)| Updated user object | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/samples/client/petstore/java/okhttp/docs/Value.md b/samples/client/petstore/java/okhttp/docs/Value.md new file mode 100644 index 000000000000..54c8fc245e72 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Value.md @@ -0,0 +1,12 @@ + + +# Value + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/petstore/java/okhttp/docs/ValuesApi.md b/samples/client/petstore/java/okhttp/docs/ValuesApi.md new file mode 100644 index 000000000000..4132ad879407 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/ValuesApi.md @@ -0,0 +1,68 @@ +# ValuesApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**getSomeValues**](ValuesApi.md#getSomeValues) | **GET** /values | Get some primitive variable values | + + + +# **getSomeValues** +> Variable getSomeValues() + +Get some primitive variable values + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.ValuesApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + ValuesApi apiInstance = new ValuesApi(defaultClient); + try { + Variable result = apiInstance.getSomeValues(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling ValuesApi#getSomeValues"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Variable**](Variable.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Value | - | + diff --git a/samples/client/petstore/java/okhttp/docs/Variable.md b/samples/client/petstore/java/okhttp/docs/Variable.md new file mode 100644 index 000000000000..d179fb1775cf --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Variable.md @@ -0,0 +1,15 @@ + + +# Variable + +Value object + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **String** | | | +|**value** | [**Value**](Value.md) | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Whale.md b/samples/client/petstore/java/okhttp/docs/Whale.md new file mode 100644 index 000000000000..30ce4bb82151 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Whale.md @@ -0,0 +1,15 @@ + + +# Whale + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**hasBaleen** | **Boolean** | | [optional] | +|**hasTeeth** | **Boolean** | | [optional] | +|**className** | **String** | | | + + + diff --git a/samples/client/petstore/java/okhttp/docs/Zebra.md b/samples/client/petstore/java/okhttp/docs/Zebra.md new file mode 100644 index 000000000000..f7c4389b6456 --- /dev/null +++ b/samples/client/petstore/java/okhttp/docs/Zebra.md @@ -0,0 +1,24 @@ + + +# Zebra + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**type** | [**TypeEnum**](#TypeEnum) | | [optional] | +|**className** | **String** | | | + + + +## Enum: TypeEnum + +| Name | Value | +|---- | -----| +| PLAINS | "plains" | +| MOUNTAIN | "mountain" | +| GREVYS | "grevys" | + + + diff --git a/samples/client/petstore/java/okhttp/git_push.sh b/samples/client/petstore/java/okhttp/git_push.sh new file mode 100644 index 000000000000..a35991cd51a1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/git_push.sh @@ -0,0 +1,54 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ -z "${git_host}" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \${git_host} to ${git_host}" +fi + +if [ -z "${git_user_id}" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \${git_user_id} to ${git_user_id}" +fi + +if [ -z "${git_repo_id}" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \${git_repo_id} to ${git_repo_id}" +fi + +if [ -z "${release_note}" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \${release_note} to ${release_note}" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "${release_note}" + +# Sets the new remote +if [ -z "$(git remote)" ]; then # git remote not defined + if [ -z "${GIT_TOKEN:-}" ]; then + echo "[INFO] \${GIT_TOKEN} (environment variable) is not set. Using the git credential in your environment." + git remote add origin "https://${git_host}/${git_user_id}/${git_repo_id}.git" + else + git remote add origin "https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git" + fi +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/java/okhttp/gradle.properties b/samples/client/petstore/java/okhttp/gradle.properties new file mode 100644 index 000000000000..a3408578278a --- /dev/null +++ b/samples/client/petstore/java/okhttp/gradle.properties @@ -0,0 +1,6 @@ +# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator). +# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option. +# +# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +# For example, uncomment below to build for Android +#target = android diff --git a/samples/client/petstore/java/okhttp/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/okhttp/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..e6441136f3d4 Binary files /dev/null and b/samples/client/petstore/java/okhttp/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/okhttp/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/okhttp/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..4f5eb9dcc0ef --- /dev/null +++ b/samples/client/petstore/java/okhttp/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.5-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/java/okhttp/gradlew b/samples/client/petstore/java/okhttp/gradlew new file mode 100644 index 000000000000..9d0ce634cb11 --- /dev/null +++ b/samples/client/petstore/java/okhttp/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while +APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path +[ -h "$app_path" ] +do +ls=$( ls -ld "$app_path" ) +link=${ls#*' -> '} +case $link in #( +/*) app_path=$link ;; #( +*) app_path=$APP_HOME$link ;; +esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { +echo "$*" +} >&2 + +die () { +echo +echo "$*" +echo +exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( +CYGWIN* ) cygwin=true ;; #( +Darwin* ) darwin=true ;; #( +MSYS* | MINGW* ) msys=true ;; #( +NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then +if [ -x "$JAVA_HOME/jre/sh/java" ] ; then +# IBM's JDK on AIX uses strange locations for the executables +JAVACMD=$JAVA_HOME/jre/sh/java +else +JAVACMD=$JAVA_HOME/bin/java +fi +if [ ! -x "$JAVACMD" ] ; then +die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +else +JAVACMD=java +if ! command -v java >/dev/null 2>&1 +then +die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then +case $MAX_FD in #( +max*) +# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +MAX_FD=$( ulimit -H -n ) || +warn "Could not query maximum file descriptor limit" +esac +case $MAX_FD in #( +'' | soft) :;; #( +*) +# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. +# shellcheck disable=SC2039,SC3045 +ulimit -n "$MAX_FD" || +warn "Could not set maximum file descriptor limit to $MAX_FD" +esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then +APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) +CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + +JAVACMD=$( cygpath --unix "$JAVACMD" ) + +# Now convert the arguments - kludge to limit ourselves to /bin/sh +for arg do +if +case $arg in #( +-*) false ;; # don't mess with options #( +/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath +[ -e "$t" ] ;; #( +*) false ;; +esac +then +arg=$( cygpath --path --ignore --mixed "$arg" ) +fi +# Roll the args list around exactly as many times as the number of +# args, so each arg winds up back in the position where it started, but +# possibly modified. +# +# NB: a `for` loop captures its iteration list before it begins, so +# changing the positional parameters here affects neither the number of +# iterations, nor the values presented in `arg`. +shift # remove old arg +set -- "$@" "$arg" # push replacement arg +done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ +"-Dorg.gradle.appname=$APP_BASE_NAME" \ +-classpath "$CLASSPATH" \ +org.gradle.wrapper.GradleWrapperMain \ +"$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then +die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( +printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | +xargs -n1 | +sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | +tr '\n' ' ' +)" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/java/okhttp/gradlew.bat b/samples/client/petstore/java/okhttp/gradlew.bat new file mode 100644 index 000000000000..25da30dbdeee --- /dev/null +++ b/samples/client/petstore/java/okhttp/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp/pom.xml b/samples/client/petstore/java/okhttp/pom.xml new file mode 100644 index 000000000000..219cbf11be4f --- /dev/null +++ b/samples/client/petstore/java/okhttp/pom.xml @@ -0,0 +1,289 @@ + + 4.0.0 + org.openapitools + petstore-okhttp + jar + petstore-okhttp + 1.0.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + https://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.4.1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + + + + + maven-dependency-plugin + 3.6.1 + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.5.0 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.6.3 + + + attach-javadocs + + jar + + + + + none + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.0 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.2.1 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + com.squareup.okhttp3 + okhttp-bom + ${okhttp-version} + pom + import + + + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + com.squareup.okhttp3 + okhttp-jvm + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + test + + + org.junit.platform + junit-platform-runner + ${junit-platform-runner.version} + test + + + + 1.8 + ${java.version} + ${java.version} + 1.9.0 + 5.4.0 + 2.10.1 + 1.3.5 + 5.10.3 + 1.10.0 + UTF-8 + + diff --git a/samples/client/petstore/java/okhttp/settings.gradle b/samples/client/petstore/java/okhttp/settings.gradle new file mode 100644 index 000000000000..3c778001cf97 --- /dev/null +++ b/samples/client/petstore/java/okhttp/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "petstore-okhttp" \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp/src/main/AndroidManifest.xml b/samples/client/petstore/java/okhttp/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..54fbcb3da1e8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiCallback.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiCallback.java new file mode 100644 index 000000000000..1bdc18fb3c11 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiCallback.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 000000000000..eab0375739b9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,1870 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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 org.openapitools.client.auth.RetryingOAuth.TokenRequestBuilder; + +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.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 org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; +import org.openapitools.client.auth.ApiKeyAuth; +import org.openapitools.client.auth.OAuth; +import org.openapitools.client.auth.RetryingOAuth; +import org.openapitools.client.auth.OAuthFlow; + +/** + *

ApiClient class.

+ */ +public class ApiClient { + + protected String basePath = "http://petstore.swagger.io:80/v2"; + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "http://{server}.swagger.io:{port}/v2", + "petstore server", + new HashMap() {{ + put("server", new ServerVariable( + "No description provided", + "petstore", + new HashSet( + Arrays.asList( + "petstore", + "qa-petstore", + "dev-petstore" + ) + ) + )); + put("port", new ServerVariable( + "No description provided", + "80", + new HashSet( + Arrays.asList( + "80", + "8080" + ) + ) + )); + }} + ), + new ServerConfiguration( + "https://localhost:8080/{version}", + "The local server", + new HashMap() {{ + put("version", new ServerVariable( + "No description provided", + "v2", + new HashSet( + Arrays.asList( + "v1", + "v2" + ) + ) + )); + }} + ), + new ServerConfiguration( + "https://127.0.0.1/no_variable", + "The local server without variables", + 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 String tlsServerName; + + 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("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key_query")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("bearer_test", new HttpBearerAuth("bearer")); + // 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("petstore_auth", new OAuth()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key_query")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("bearer_test", new HttpBearerAuth("bearer")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID + * + * @param clientId client ID + */ + public ApiClient(String clientId) { + this(clientId, null, null); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID and additional parameters + * + * @param clientId client ID + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, Map parameters) { + this(clientId, null, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID, secret, and additional parameters + * + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, String clientSecret, Map parameters) { + this(null, clientId, clientSecret, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters + * + * @param basePath base path + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String basePath, String clientId, String clientSecret, Map parameters) { + init(); + if (basePath != null) { + this.basePath = basePath; + } + + String tokenUrl = ""; + if (!"".equals(tokenUrl) && !URI.create(tokenUrl).isAbsolute()) { + URI uri = URI.create(getBasePath()); + tokenUrl = uri.getScheme() + ":" + + (uri.getAuthority() != null ? "//" + uri.getAuthority() : "") + + tokenUrl; + if (!URI.create(tokenUrl).isAbsolute()) { + throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL"); + } + } + RetryingOAuth retryingOAuth = new RetryingOAuth(tokenUrl, clientId, OAuthFlow.IMPLICIT, clientSecret, parameters); + authentications.put( + "petstore_auth", + retryingOAuth + ); + initHttpClient(Collections.singletonList(retryingOAuth)); + // Setup authentications (key: authentication name, value: authentication). + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key_query")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("bearer_test", new HttpBearerAuth("bearer")); + + // 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/1.0.0/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://petstore.swagger.io:80/v2) + * @return An instance of ApiClient + */ + 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 ApiClient + * @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; + } + + /** + * Get TLS server name for SNI (Server Name Indication). + * + * @return The TLS server name + */ + public String getTlsServerName() { + return tlsServerName; + } + + /** + * Set TLS server name for SNI (Server Name Indication). + * This is used to verify the server certificate against a specific hostname + * instead of the hostname in the URL. + * + * @param tlsServerName The TLS server name to use for certificate verification + * @return ApiClient + */ + public ApiClient setTlsServerName(String tlsServerName) { + this.tlsServerName = tlsServerName; + 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 org.openapitools.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 org.openapitools.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 org.openapitools.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 org.openapitools.client.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + + /** + *

Set LocalDateTimeFormat.

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

Set LenientOnJson.

+ * + * @param lenientOnJson a boolean + * @return a {@link org.openapitools.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 access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + setBearerToken(() -> bearerToken); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier The supplier of bearer tokens + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * 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) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + 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; + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * + * @return Token request builder + */ + public TokenRequestBuilder getTokenEndPoint() { + for (Authentication apiAuth : authentications.values()) { + if (apiAuth instanceof RetryingOAuth) { + RetryingOAuth retryingOAuth = (RetryingOAuth) apiAuth; + return retryingOAuth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * 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); + } + } + + /** + * Format the given parameter object as an ASCII-safe JSON string. + * + * @param param Parameter + * @return JSON representation of the parameter + */ + public String parameterToJsonString(Object param) { + if (param == null) { + return ""; + } + String json = this.json.serialize(param); + int firstUnsafe = -1; + for (int i = 0; i < json.length(); i++) { + if (json.charAt(i) >= 0x7f) { + firstUnsafe = i; + break; + } + } + if (firstUnsafe == -1) { + return json; + } + + StringBuilder escaped = new StringBuilder(json.length()); + escaped.append(json, 0, firstUnsafe); + for (int i = firstUnsafe; i < json.length(); i++) { + char c = json.charAt(i); + if (c >= 0x7f) { + escaped.append("\\u"); + escaped.append(Character.forDigit((c >> 12) & 0xf, 16)); + escaped.append(Character.forDigit((c >> 8) & 0xf, 16)); + escaped.append(Character.forDigit((c >> 4) & 0xf, 16)); + escaped.append(Character.forDigit(c & 0xf, 16)); + } else { + escaped.append(c); + } + } + + return escaped.toString(); + } + + /** + * 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; + } + + // escape all delimiters except commas, which are URI reserved characters + String separator = collectionFormatSeparator(collectionFormat); + String delimiter = ",".equals(separator) ? separator : escapeString(separator); + + 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); + } + + String delimiter = collectionFormatSeparator(collectionFormat); + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Returns the separator between the items of a collection serialized in the + * given collection format. + * + * @param collectionFormat The collection format of the parameter ("csv" when unrecognized). + * @return The separator string. + */ + protected String collectionFormatSeparator(String collectionFormat) { + if ("ssv".equals(collectionFormat)) { + return " "; + } else if ("tsv".equals(collectionFormat)) { + return "\t"; + } else if ("pipes".equals(collectionFormat)) { + return "|"; + } + // collectionFormat is assumed to be "csv" by default + return ","; + } + + /** + * 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 org.openapitools.client.ApiException If fail to deserialize response body, i.e. cannot read response body, + * the body does not match the return type, or the Content-Type of the response is not supported. + * The exception carries the status code and headers of the response. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if (byte[].class.equals(returnType) || "byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e.getMessage(), e, response.code(), response.headers().toMultimap()); + } + } 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)) { + if (returnType.equals(String.class)) { + String respBodyString = respBody.string(); + if (respBodyString.isEmpty()) { + return null; + } + // Use String-based deserialize for String return type with fallback + return json.deserialize(respBodyString, returnType); + } else { + // Use InputStream-based deserialize which supports responses > 2GB + 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 | RuntimeException e) { + // The body could not be read or does not match the expected type. Serializers report + // that differently, some with an unchecked exception and some with an IOException, + // so it is always surfaced as an ApiException + // that keeps the status and headers of the response it belongs to. The body itself + // was consumed as a stream and is not available any more. + throw new ApiException( + "Failed to deserialize the response body as " + returnType + ": " + e.getMessage(), + e, + response.code(), + response.headers().toMultimap()); + } + } + + /** + * 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 org.openapitools.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 org.openapitools.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); + try(ResponseBody body = response.body(); BufferedSink sink = Okio.buffer(Okio.sink(file))) { + sink.writeAll(body.source()); + } + 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 org.openapitools.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 org.openapitools.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()); + response.close(); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + response.close(); + 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 org.openapitools.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 org.openapitools.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 org.openapitools.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); + + byte[] localVarPayload = requestBodyToBytes(reqBody); + + // update parameters with authentication settings + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RuntimeException("Authentication undefined: " + authName); + } + URI currentUri = URI.create(buildUrl(baseUrl, path, updatedQueryParams, collectionQueryParams)); + auth.applyToParams(updatedQueryParams, headerParams, cookieParams, localVarPayload, method, currentUri); + } + + 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( + java.util.Locale.ROOT, + "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(java.util.Locale.ROOT, "%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format(java.util.Locale.ROOT, "%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * 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 { + trustManagers = trustedTrustManagers(); + hostnameVerifier = trustedHostnameVerifier(); + } + + 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); + } + } + + /** + * Build the trust managers that verify server certificates against the JVM's + * trust store, or against sslCaCert when one is configured. + * + * @return The trust managers to initialize the client's SSLContext with + * @throws GeneralSecurityException if sslCaCert cannot be loaded into a key store + */ + protected TrustManager[] trustedTrustManagers() throws GeneralSecurityException { + 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); + } + return trustManagerFactory.getTrustManagers(); + } + + /** + * Build the hostname verifier for TLS connections, honoring tlsServerName when set. + * + * @return The hostname verifier to configure the http client with + */ + protected HostnameVerifier trustedHostnameVerifier() { + if (tlsServerName != null && !tlsServerName.isEmpty()) { + return new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + // Verify the certificate against tlsServerName instead of the actual hostname + return OkHostnameVerifier.INSTANCE.verify(tlsServerName, session); + } + }; + } + return OkHostnameVerifier.INSTANCE; + } + + 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 byte array. + * + * @param requestBody The HTTP request object + * @return The byte array representation of the HTTP request body + * @throws org.openapitools.client.ApiException If fail to serialize the request body object into a byte array + */ + protected byte[] requestBodyToBytes(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readByteArray(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return new byte[0]; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiException.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 000000000000..72448421d614 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,167 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; +import java.util.List; + + +/** + *

ApiException class.

+ */ +@SuppressWarnings("serial") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +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.

+ */ + public ApiException() {} + + /** + *

Constructor for ApiException.

+ * + * @param throwable a {@link java.lang.Throwable} object + */ + public ApiException(Throwable throwable) { + super(throwable); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + */ + public ApiException(String message) { + super(message); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, Map> responseHeaders, String responseBody) { + this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message a {@link java.lang.String} object + */ + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + /** + *

Constructor for ApiException.

+ * + * @param code HTTP status code + * @param message the error message + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } + + /** + * Get the exception message including HTTP response data. + * + * @return The exception message + */ + public String getMessage() { + return String.format(java.util.Locale.ROOT, "Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", + super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders()); + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiResponse.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiResponse.java new file mode 100644 index 000000000000..37651488424f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ApiResponse.java @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + */ +public class ApiResponse { + private final int statusCode; + private final Map> headers; + private final T data; + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + *

Constructor for ApiResponse.

+ * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response body + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + /** + *

Get the status code.

+ * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

Get the headers.

+ * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

Get the data.

+ * + * @return the data + */ + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/Configuration.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/Configuration.java new file mode 100644 index 000000000000..963d7856fda0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/Configuration.java @@ -0,0 +1,63 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +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.28.0-SNAPSHOT") +public class Configuration { + public static final String VERSION = "1.0.0"; + + private static final AtomicReference defaultApiClient = new AtomicReference<>(); + private static volatile Supplier apiClientFactory = ApiClient::new; + + /** + * 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/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/GzipRequestInterceptor.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/GzipRequestInterceptor.java new file mode 100644 index 000000000000..3fc4d30d8b74 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/GzipRequestInterceptor.java @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + + /** + * Number of bytes handed to the sink per write while replaying a buffered body. Replaying the + * whole body in a single write would collapse an upload into one progress event, so it is + * replayed one okio segment at a time instead. + */ + private static final long WRITE_CHUNK_SIZE = 8192L; + + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + RequestBody body = originalRequest.body(); + if (body == null || originalRequest.header("Content-Encoding") != null || body.contentLength() == 0) { + return chain.proceed(originalRequest); + } + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), compress(body)) + .build(); + return chain.proceed(compressedRequest); + } + + /** + * Compresses the request body while keeping upload progress reporting truthful. + * + *

Compressing drains the body up front (see {@link #forceContentLength}). Draining a + * {@link ProgressRequestBody} here would fire every upload callback, the terminal one included, + * before a single byte reached the socket, and would report the uncompressed sizes. So the body + * that the {@code ProgressRequestBody} wraps is compressed instead, and the compressed bytes are + * re-wrapped with the same callback: progress is then reported against the bytes that are + * actually transmitted, as they are transmitted. + */ + private RequestBody compress(final RequestBody body) throws IOException { + if (body instanceof ProgressRequestBody) { + ProgressRequestBody progressBody = (ProgressRequestBody) body; + return new ProgressRequestBody(forceContentLength(gzip(progressBody.getDelegate())), progressBody.getCallback()); + } + return forceContentLength(gzip(body)); + } + + /** + * The gzip body reports an unknown content length, which makes OkHttp fall back to + * "Transfer-Encoding: chunked". Servers that reject chunked request bodies then fail every + * compressed request, so buffer the compressed bytes and republish their known length. + * + *

Known limitation: the compressed body is held in memory until the request completes, so a + * very large upload can exhaust the heap. Publishing the compressed length requires compressing + * the whole body first, so the buffering is inherent to the behaviour above; clients that upload + * bodies too large to buffer should leave gzip request compression disabled. + */ + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + // clone() shares the buffered segments instead of copying them, so the body stays + // replayable (OkHttp may re-send it after a redirect or an auth challenge) without + // a second copy of the payload. Write it out in chunks so that an enclosing + // ProgressRequestBody sees the upload advance rather than one all-at-once event. + Buffer source = buffer.clone(); + while (!source.exhausted()) { + sink.write(source, Math.min(source.size(), WRITE_CHUNK_SIZE)); + } + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/JSON.java new file mode 100644 index 000000000000..1eba33300ee5 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/JSON.java @@ -0,0 +1,762 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import org.openapitools.client.model.AbstractOpenApiSchema; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; + + +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; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; +import java.util.Date; +import java.util.Set; +import java.util.Map; + +/* + * A JSON utility class + */ +public class JSON { + private static Gson gson; + private static boolean isLenientOnJson = false; + private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private static LocalDateTimeTypeAdapter localDateTimeTypeAdapter = new LocalDateTimeTypeAdapter(); + private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + + static { + ensureInitialized(); + } + + public JSON() { + ensureInitialized(); + } + + private static synchronized void ensureInitialized() { + if (gson != null) { + // the shared static Gson is already built; rebuilding would discard a + // customization installed through setGson() + return; + } + GsonFireBuilder fireBuilder = new GsonFireBuilder(); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Animal.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class); + classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class); + classByDiscriminatorValue.put("Animal", org.openapitools.client.model.Animal.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Cat.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Dog.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.EnumStringDiscriminator.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("EnumStringDiscriminator", org.openapitools.client.model.EnumStringDiscriminator.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "enum_str_type")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.GrandparentAnimal.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("ParentPet", org.openapitools.client.model.ParentPet.class); + classByDiscriminatorValue.put("GrandparentAnimal", org.openapitools.client.model.GrandparentAnimal.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "pet_type")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Mammal.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Pig", org.openapitools.client.model.Pig.class); + classByDiscriminatorValue.put("whale", org.openapitools.client.model.Whale.class); + classByDiscriminatorValue.put("zebra", org.openapitools.client.model.Zebra.class); + classByDiscriminatorValue.put("mammal", org.openapitools.client.model.Mammal.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.MammalAnyof.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Pig", org.openapitools.client.model.Pig.class); + classByDiscriminatorValue.put("whale", org.openapitools.client.model.Whale.class); + classByDiscriminatorValue.put("zebra", org.openapitools.client.model.Zebra.class); + classByDiscriminatorValue.put("mammal_anyof", org.openapitools.client.model.MammalAnyof.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.NullableShape.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + classByDiscriminatorValue.put("NullableShape", org.openapitools.client.model.NullableShape.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "shapeType")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.ParentPet.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("ParentPet", org.openapitools.client.model.ParentPet.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "pet_type")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Pig.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("BasquePig", org.openapitools.client.model.BasquePig.class); + classByDiscriminatorValue.put("DanishPig", org.openapitools.client.model.DanishPig.class); + classByDiscriminatorValue.put("Pig", org.openapitools.client.model.Pig.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Quadrilateral.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("ComplexQuadrilateral", org.openapitools.client.model.ComplexQuadrilateral.class); + classByDiscriminatorValue.put("SimpleQuadrilateral", org.openapitools.client.model.SimpleQuadrilateral.class); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "quadrilateralType")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Shape.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + classByDiscriminatorValue.put("Shape", org.openapitools.client.model.Shape.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "shapeType")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.ShapeOrNull.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + classByDiscriminatorValue.put("ShapeOrNull", org.openapitools.client.model.ShapeOrNull.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "shapeType")); + } + }); + fireBuilder.registerTypeSelector(org.openapitools.client.model.Triangle.class, new io.gsonfire.TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new java.util.HashMap(); + classByDiscriminatorValue.put("EquilateralTriangle", org.openapitools.client.model.EquilateralTriangle.class); + classByDiscriminatorValue.put("IsoscelesTriangle", org.openapitools.client.model.IsoscelesTriangle.class); + classByDiscriminatorValue.put("ScaleneTriangle", org.openapitools.client.model.ScaleneTriangle.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "triangleType")); + } + }); + GsonBuilder builder = fireBuilder.createGsonBuilder(); + builder.registerTypeAdapter(Date.class, dateTypeAdapter); + builder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); + builder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); + builder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); + builder.registerTypeAdapter(LocalDateTime.class, localDateTimeTypeAdapter); + builder.registerTypeAdapter(byte[].class, byteArrayAdapter); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesClass.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOf.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfAttributes.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfAttributesC.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1Value.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfRefToDouble.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfRefToFloat.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfRefToLong.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Apple.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.AppleReq.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayAnyOf.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayDefault.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfArrayOfNumberOnly.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfInlineAllOf.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfInlineAllOfArrayAllofDogPropertyInner.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfNumberOnly.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOneOf.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayTest.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Banana.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.BananaReq.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.BasquePig.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Capitalization.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Cat.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Category.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ClassModel.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Client.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ComplexQuadrilateral.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.DanishPig.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.DeprecatedObject.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Dog.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Drawing.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.EnumArrays.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.EnumStringDiscriminator.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.EnumTest.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.EquilateralTriangle.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FakeAnyOfWIthSameErasureGet200Response.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FakeOneOfWIthSameErasureGet200Response.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FakeRefParameterPetIdParameter.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FileSchemaTestClass.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Foo.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FooGetDefaultResponse.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FormatTest.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FreeFormObjectTestClass.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FreeFormObjectTestClassProperties.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Fruit.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.FruitReq.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.GmFruit.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.HasOnlyReadOnly.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.HealthCheckResult.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.IsoscelesTriangle.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Mammal.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.MammalAnyof.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.MapTest.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.MixedPropertiesAndAdditionalPropertiesClass.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Model200Response.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelApiResponse.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelFile.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelList.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelReturn.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ModelWithOneOfAnyOfProperties.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Name.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NestedArrayWithDefaultValues.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPet.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPetCategoryInlineAllof.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPetCategoryInlineAllofAllOfCategoryTag.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableClass.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsMapError.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsMapResponse.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsMapSuccess.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsValue.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableShape.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.NumberOnly.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ObjectWithDeprecatedFields.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Order.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.OuterComposite.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ParentPet.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Pet.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.PetComposition.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.PetRef.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.PetUsingAllOf.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.PetWithRequiredTags.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Pig.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.PropertyNameCollision.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Quadrilateral.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.QuadrilateralInterface.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ReadOnlyFirst.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.RequiredNullableBody.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Scalar.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ScalarAnyOf.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ScaleneTriangle.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Shape.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ShapeInterface.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.ShapeOrNull.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.SimpleQuadrilateral.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.SpecialModelName.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Tag.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.TestInlineFreeformAdditionalPropertiesRequest.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Triangle.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.TriangleInterface.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.User.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Value.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Variable.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Whale.CustomTypeAdapterFactory()); + builder.registerTypeAdapterFactory(new org.openapitools.client.model.Zebra.CustomTypeAdapterFactory()); + gson = builder.create(); + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + + /** + * Get the internal serialization object. + * + * @return serialization object + */ + public static Object getSerializer() { + return gson; + } + + /** + * Set the internal serialization object. + * + * @param serializer serialization object + */ + public static void setSerializer(Object serializer) { + JSON.gson = (Gson) serializer; + } + + public static Gson getGson() { + return gson; + } + + public static void setGson(Gson gson) { + JSON.gson = gson; + } + + public static void setLenientOnJson(boolean lenientOnJson) { + JSON.isLenientOnJson = lenientOnJson; + } + + public static void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } + + public static boolean isInstanceOf(Class type, Object instance, Set> visited) { + if (instance == null) { + // null never matches a concrete schema type; nullable composed schemas accept + // null in setActualInstance before consulting this method + return false; + } + if (type.isInstance(instance)) { + return true; + } + if (instance instanceof AbstractOpenApiSchema) { + AbstractOpenApiSchema schema = (AbstractOpenApiSchema) instance; + visited.add(schema.getClass()); + for (Class allowedType : schema.getSchemas().values()) { + if (visited.contains(allowedType)) { + continue; + } + if (isInstanceOf(type, schema.getActualInstance(), visited)) { + return true; + } + } + } + return false; + } + + + + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + } + + /** + * 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 T deserialize(InputStream inputStream, Type returnType) throws IOException { + try (InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8)) { + if (isLenientOnJson) { + 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 + */ + public static class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public static class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public static class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDateTime type + */ + public static class LocalDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE_TIME); + } + + public LocalDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + return LocalDateTime.parse(date, formatter); + } catch (DateTimeParseException e) { + if (date.length() > 10 && date.charAt(10) == ' ') { + date = date.substring(0, 10) + 'T' + date.substring(11); + return LocalDateTime.parse(date, formatter); + } + throw e; + } + } + } + } + + public static void setLocalDateTimeFormat(DateTimeFormatter dateFormat) { + localDateTimeTypeAdapter.setFormat(dateFormat); + } + + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public static class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public static class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/Pair.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 000000000000..ab40b606e833 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Pair { + private final String name; + private final String value; + + public Pair(String name, String value) { + this.name = isValidString(name) ? name : ""; + this.value = isValidString(value) ? value : ""; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private static boolean isValidString(String arg) { + return arg != null; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ProgressRequestBody.java new file mode 100644 index 000000000000..46787dc0eb94 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ProgressRequestBody.java @@ -0,0 +1,130 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; +import java.util.Objects; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = Objects.requireNonNull(callback); + } + + /** + * The body this one wraps. Package-private so that {@link GzipRequestInterceptor} can compress + * that body directly: draining this wrapper to compress it would report the upload as finished + * before the request reached the network. + * + * @return the wrapped request body + */ + RequestBody getDelegate() { + return requestBody; + } + + /** + * The callback this body reports upload progress to. Package-private so that + * {@link GzipRequestInterceptor} can re-wrap the compressed body with the same callback. + * + * @return the progress callback + */ + ApiCallback getCallback() { + return callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public boolean isDuplex() { + return requestBody.isDuplex(); + } + + @Override + public boolean isOneShot() { + return requestBody.isOneShot(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + if (isDuplex()) { + // A duplex body may keep writing on another thread after writeTo() returns, so completion + // can only be reported once the delegate closes the sink, not when this method returns. + requestBody.writeTo(Okio.buffer(new CountingSink(sink, true))); + return; + } + CountingSink countingSink = new CountingSink(sink, false); + BufferedSink bufferedSink = Okio.buffer(countingSink); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + + long bytesWritten = countingSink.bytesWritten; + long contentLength = contentLength(); + callback.onUploadProgress(bytesWritten, contentLength, true); + } + + private final class CountingSink extends ForwardingSink { + + private long bytesWritten = 0L; + private long contentLength = 0L; + private final boolean reportDoneOnClose; + + public CountingSink(Sink delegate, boolean reportDoneOnClose) { + super(delegate); + this.reportDoneOnClose = reportDoneOnClose; + } + + @Override + public void close() throws IOException { + super.close(); + if (reportDoneOnClose) { + callback.onUploadProgress(bytesWritten, contentLength == 0 ? contentLength() : contentLength, true); + } + } + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + // writeTo emits the single terminal callback once the body is fully written; reporting + // done here as well would fire it twice for a known-length body. + callback.onUploadProgress(bytesWritten, contentLength, false); + } + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ProgressResponseBody.java new file mode 100644 index 000000000000..dfe04c1a1e13 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ProgressResponseBody.java @@ -0,0 +1,82 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + // Memoized: OkHttp calls source() again on close(), and a second ForwardingSource would + // reset the progress counter and re-wrap an already partially consumed stream. + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + boolean done = false; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + if (bytesRead == -1) { + // an exhausted source keeps answering -1 to every further read (a buffered + // reader probes it more than once), so completion is reported only once + if (!done) { + done = true; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), true); + } + return bytesRead; + } + totalBytesRead += bytesRead; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), false); + return bytesRead; + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 000000000000..0a8c0e35bddb --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,72 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ServerVariable.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 000000000000..efef4b0f5632 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/StringUtil.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 000000000000..8bfbeead82b3 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/AnotherFakeApi.java new file mode 100644 index 000000000000..2d866151e23a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -0,0 +1,454 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AnotherFakeApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public AnotherFakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public AnotherFakeApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for call123testSpecialTags + * @param client client model (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 successful operation -
+ */ + public okhttp3.Call call123testSpecialTagsCall(@javax.annotation.Nonnull Client client, 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 = client; + + // create path and map variables + String localVarPath = "/another-fake/dummy"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call call123testSpecialTagsValidateBeforeCall(@javax.annotation.Nonnull Client client, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'client' is set + if (client == null) { + throw new ApiException("Missing the required parameter 'client' when calling call123testSpecialTags(Async)"); + } + + return call123testSpecialTagsCall(client, _callback); + + } + + /** + * To test special tags + * To test special tags and operation ID starting with number + * @param client client model (required) + * @return Client + * @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 successful operation -
+ */ + public Client call123testSpecialTags(@javax.annotation.Nonnull Client client) throws ApiException { + ApiResponse localVarResp = call123testSpecialTagsWithHttpInfo(client); + return localVarResp.getData(); + } + + /** + * To test special tags + * To test special tags and operation ID starting with number + * @param client client model (required) + * @return ApiResponse<Client> + * @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 successful operation -
+ */ + public ApiResponse call123testSpecialTagsWithHttpInfo(@javax.annotation.Nonnull Client client) throws ApiException { + okhttp3.Call localVarCall = call123testSpecialTagsValidateBeforeCall(client, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * To test special tags (asynchronously) + * To test special tags and operation ID starting with number + * @param client client model (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 successful operation -
+ */ + public okhttp3.Call call123testSpecialTagsAsync(@javax.annotation.Nonnull Client client, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = call123testSpecialTagsValidateBeforeCall(client, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getParameterArrayNumber + * @param array array integer (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 getParameterArrayNumberCall(@javax.annotation.Nonnull List array, 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 = "/fake/parameter-array-number"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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); + } + + if (array != null) { + localVarHeaderParams.put("array", localVarApiClient.parameterToString(array)); + } + + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getParameterArrayNumberValidateBeforeCall(@javax.annotation.Nonnull List array, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'array' is set + if (array == null) { + throw new ApiException("Missing the required parameter 'array' when calling getParameterArrayNumber(Async)"); + } + + return getParameterArrayNumberCall(array, _callback); + + } + + /** + * parameter array number default value + * + * @param array array integer (required) + * @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 void getParameterArrayNumber(@javax.annotation.Nonnull List array) throws ApiException { + getParameterArrayNumberWithHttpInfo(array); + } + + /** + * parameter array number default value + * + * @param array array integer (required) + * @return ApiResponse<Void> + * @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 getParameterArrayNumberWithHttpInfo(@javax.annotation.Nonnull List array) throws ApiException { + okhttp3.Call localVarCall = getParameterArrayNumberValidateBeforeCall(array, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * parameter array number default value (asynchronously) + * + * @param array array integer (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 getParameterArrayNumberAsync(@javax.annotation.Nonnull List array, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getParameterArrayNumberValidateBeforeCall(array, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for getParameterStringNumber + * @param stringNumber string number (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 getParameterStringNumberCall(@javax.annotation.Nonnull BigDecimal stringNumber, 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 = "/fake/parameter-string-number"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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); + } + + if (stringNumber != null) { + localVarHeaderParams.put("string_number", localVarApiClient.parameterToString(stringNumber)); + } + + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getParameterStringNumberValidateBeforeCall(@javax.annotation.Nonnull BigDecimal stringNumber, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'stringNumber' is set + if (stringNumber == null) { + throw new ApiException("Missing the required parameter 'stringNumber' when calling getParameterStringNumber(Async)"); + } + + return getParameterStringNumberCall(stringNumber, _callback); + + } + + /** + * parameter string number + * + * @param stringNumber string number (required) + * @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 void getParameterStringNumber(@javax.annotation.Nonnull BigDecimal stringNumber) throws ApiException { + getParameterStringNumberWithHttpInfo(stringNumber); + } + + /** + * parameter string number + * + * @param stringNumber string number (required) + * @return ApiResponse<Void> + * @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 getParameterStringNumberWithHttpInfo(@javax.annotation.Nonnull BigDecimal stringNumber) throws ApiException { + okhttp3.Call localVarCall = getParameterStringNumberValidateBeforeCall(stringNumber, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * parameter string number (asynchronously) + * + * @param stringNumber string number (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 getParameterStringNumberAsync(@javax.annotation.Nonnull BigDecimal stringNumber, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getParameterStringNumberValidateBeforeCall(stringNumber, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/DefaultApi.java new file mode 100644 index 000000000000..69e7113e8406 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -0,0 +1,559 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import org.openapitools.client.model.FakeAnyOfWIthSameErasureGet200Response; +import org.openapitools.client.model.FakeOneOfWIthSameErasureGet200Response; +import org.openapitools.client.model.FooGetDefaultResponse; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DefaultApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public DefaultApi() { + this(Configuration.getDefaultApiClient()); + } + + public DefaultApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for fakeAnyOfWIthSameErasureGet + * @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 successful response -
+ */ + public okhttp3.Call fakeAnyOfWIthSameErasureGetCall(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 = "/fake/anyOfWIthSameErasure"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeAnyOfWIthSameErasureGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return fakeAnyOfWIthSameErasureGetCall(_callback); + + } + + /** + * + * Test route, this shouldn't cause a compiler error + * @return FakeAnyOfWIthSameErasureGet200Response + * @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 successful response -
+ */ + public FakeAnyOfWIthSameErasureGet200Response fakeAnyOfWIthSameErasureGet() throws ApiException { + ApiResponse localVarResp = fakeAnyOfWIthSameErasureGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * Test route, this shouldn't cause a compiler error + * @return ApiResponse<FakeAnyOfWIthSameErasureGet200Response> + * @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 successful response -
+ */ + public ApiResponse fakeAnyOfWIthSameErasureGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fakeAnyOfWIthSameErasureGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test route, this shouldn't cause a compiler error + * @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 successful response -
+ */ + public okhttp3.Call fakeAnyOfWIthSameErasureGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeAnyOfWIthSameErasureGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeFreeFormQueryParametersGet + * @param fixed (optional) + * @param freeForm (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 fakeFreeFormQueryParametersGetCall(@javax.annotation.Nullable String fixed, @javax.annotation.Nullable Object freeForm, 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 = "/fake/free-form-query-parameters"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (fixed != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("fixed", fixed)); + } + + if (freeForm != null) { + localVarQueryParams.addAll(localVarApiClient.freeFormParameterToPairs(freeForm)); + } + + final String[] localVarAccepts = { + }; + 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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeFreeFormQueryParametersGetValidateBeforeCall(@javax.annotation.Nullable String fixed, @javax.annotation.Nullable Object freeForm, final ApiCallback _callback) throws ApiException { + return fakeFreeFormQueryParametersGetCall(fixed, freeForm, _callback); + + } + + /** + * + * + * @param fixed (optional) + * @param freeForm (optional) + * @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 void fakeFreeFormQueryParametersGet(@javax.annotation.Nullable String fixed, @javax.annotation.Nullable Object freeForm) throws ApiException { + fakeFreeFormQueryParametersGetWithHttpInfo(fixed, freeForm); + } + + /** + * + * + * @param fixed (optional) + * @param freeForm (optional) + * @return ApiResponse<Void> + * @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 fakeFreeFormQueryParametersGetWithHttpInfo(@javax.annotation.Nullable String fixed, @javax.annotation.Nullable Object freeForm) throws ApiException { + okhttp3.Call localVarCall = fakeFreeFormQueryParametersGetValidateBeforeCall(fixed, freeForm, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * + * @param fixed (optional) + * @param freeForm (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 fakeFreeFormQueryParametersGetAsync(@javax.annotation.Nullable String fixed, @javax.annotation.Nullable Object freeForm, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeFreeFormQueryParametersGetValidateBeforeCall(fixed, freeForm, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for fakeOneOfWIthSameErasureGet + * @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 successful response -
+ */ + public okhttp3.Call fakeOneOfWIthSameErasureGetCall(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 = "/fake/oneOfWIthSameErasure"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOneOfWIthSameErasureGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return fakeOneOfWIthSameErasureGetCall(_callback); + + } + + /** + * + * Test route, this shouldn't cause a compiler error + * @return FakeOneOfWIthSameErasureGet200Response + * @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 successful response -
+ */ + public FakeOneOfWIthSameErasureGet200Response fakeOneOfWIthSameErasureGet() throws ApiException { + ApiResponse localVarResp = fakeOneOfWIthSameErasureGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * Test route, this shouldn't cause a compiler error + * @return ApiResponse<FakeOneOfWIthSameErasureGet200Response> + * @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 successful response -
+ */ + public ApiResponse fakeOneOfWIthSameErasureGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fakeOneOfWIthSameErasureGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test route, this shouldn't cause a compiler error + * @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 successful response -
+ */ + public okhttp3.Call fakeOneOfWIthSameErasureGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOneOfWIthSameErasureGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fooGet + * @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
0 response -
+ */ + public okhttp3.Call fooGetCall(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 = "/foo"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fooGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return fooGetCall(_callback); + + } + + /** + * + * + * @return FooGetDefaultResponse + * @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
0 response -
+ */ + public FooGetDefaultResponse fooGet() throws ApiException { + ApiResponse localVarResp = fooGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * + * @return ApiResponse<FooGetDefaultResponse> + * @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
0 response -
+ */ + public ApiResponse fooGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fooGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @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
0 response -
+ */ + public okhttp3.Call fooGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fooGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/FakeApi.java new file mode 100644 index 000000000000..0189ee72a4d7 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/FakeApi.java @@ -0,0 +1,3453 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.FakeRefParameterPetIdParameter; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.FreeFormObjectTestClass; +import org.openapitools.client.model.HealthCheckResult; +import java.time.LocalDate; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.NullableFieldsMapResponse; +import java.time.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.RequiredNullableBody; +import org.openapitools.client.model.TestInlineFreeformAdditionalPropertiesRequest; +import org.openapitools.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for fakeGetFreeFormObjectGet + * @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 Success -
+ */ + public okhttp3.Call fakeGetFreeFormObjectGetCall(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 = "/fake/get-free-form-object"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeGetFreeFormObjectGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return fakeGetFreeFormObjectGetCall(_callback); + + } + + /** + * + * Get a free form object or Json string + * @return FreeFormObjectTestClass + * @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 Success -
+ */ + public FreeFormObjectTestClass fakeGetFreeFormObjectGet() throws ApiException { + ApiResponse localVarResp = fakeGetFreeFormObjectGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * Get a free form object or Json string + * @return ApiResponse<FreeFormObjectTestClass> + * @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 Success -
+ */ + public ApiResponse fakeGetFreeFormObjectGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fakeGetFreeFormObjectGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Get a free form object or Json string + * @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 Success -
+ */ + public okhttp3.Call fakeGetFreeFormObjectGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeGetFreeFormObjectGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterBooleanSerialize + * @param body Input boolean as post body (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 Output boolean -
+ */ + public okhttp3.Call fakeOuterBooleanSerializeCall(@javax.annotation.Nullable Boolean body, 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 = body; + + // create path and map variables + String localVarPath = "/fake/outer/boolean"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterBooleanSerializeValidateBeforeCall(@javax.annotation.Nullable Boolean body, final ApiCallback _callback) throws ApiException { + return fakeOuterBooleanSerializeCall(body, _callback); + + } + + /** + * + * Test serialization of outer boolean types + * @param body Input boolean as post body (optional) + * @return Boolean + * @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 Output boolean -
+ */ + public Boolean fakeOuterBooleanSerialize(@javax.annotation.Nullable Boolean body) throws ApiException { + ApiResponse localVarResp = fakeOuterBooleanSerializeWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * + * Test serialization of outer boolean types + * @param body Input boolean as post body (optional) + * @return ApiResponse<Boolean> + * @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 Output boolean -
+ */ + public ApiResponse fakeOuterBooleanSerializeWithHttpInfo(@javax.annotation.Nullable Boolean body) throws ApiException { + okhttp3.Call localVarCall = fakeOuterBooleanSerializeValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of outer boolean types + * @param body Input boolean as post body (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 Output boolean -
+ */ + public okhttp3.Call fakeOuterBooleanSerializeAsync(@javax.annotation.Nullable Boolean body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterBooleanSerializeValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterCompositeSerialize + * @param outerComposite Input composite as post body (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 Output composite -
+ */ + public okhttp3.Call fakeOuterCompositeSerializeCall(@javax.annotation.Nullable OuterComposite outerComposite, 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 = outerComposite; + + // create path and map variables + String localVarPath = "/fake/outer/composite"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterCompositeSerializeValidateBeforeCall(@javax.annotation.Nullable OuterComposite outerComposite, final ApiCallback _callback) throws ApiException { + return fakeOuterCompositeSerializeCall(outerComposite, _callback); + + } + + /** + * + * Test serialization of object with outer number type + * @param outerComposite Input composite as post body (optional) + * @return OuterComposite + * @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 Output composite -
+ */ + public OuterComposite fakeOuterCompositeSerialize(@javax.annotation.Nullable OuterComposite outerComposite) throws ApiException { + ApiResponse localVarResp = fakeOuterCompositeSerializeWithHttpInfo(outerComposite); + return localVarResp.getData(); + } + + /** + * + * Test serialization of object with outer number type + * @param outerComposite Input composite as post body (optional) + * @return ApiResponse<OuterComposite> + * @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 Output composite -
+ */ + public ApiResponse fakeOuterCompositeSerializeWithHttpInfo(@javax.annotation.Nullable OuterComposite outerComposite) throws ApiException { + okhttp3.Call localVarCall = fakeOuterCompositeSerializeValidateBeforeCall(outerComposite, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of object with outer number type + * @param outerComposite Input composite as post body (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 Output composite -
+ */ + public okhttp3.Call fakeOuterCompositeSerializeAsync(@javax.annotation.Nullable OuterComposite outerComposite, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterCompositeSerializeValidateBeforeCall(outerComposite, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterNumberSerialize + * @param body Input number as post body (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 Output number -
+ */ + public okhttp3.Call fakeOuterNumberSerializeCall(@javax.annotation.Nullable BigDecimal body, 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 = body; + + // create path and map variables + String localVarPath = "/fake/outer/number"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterNumberSerializeValidateBeforeCall(@javax.annotation.Nullable BigDecimal body, final ApiCallback _callback) throws ApiException { + return fakeOuterNumberSerializeCall(body, _callback); + + } + + /** + * + * Test serialization of outer number types + * @param body Input number as post body (optional) + * @return BigDecimal + * @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 Output number -
+ */ + public BigDecimal fakeOuterNumberSerialize(@javax.annotation.Nullable BigDecimal body) throws ApiException { + ApiResponse localVarResp = fakeOuterNumberSerializeWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * + * Test serialization of outer number types + * @param body Input number as post body (optional) + * @return ApiResponse<BigDecimal> + * @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 Output number -
+ */ + public ApiResponse fakeOuterNumberSerializeWithHttpInfo(@javax.annotation.Nullable BigDecimal body) throws ApiException { + okhttp3.Call localVarCall = fakeOuterNumberSerializeValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of outer number types + * @param body Input number as post body (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 Output number -
+ */ + public okhttp3.Call fakeOuterNumberSerializeAsync(@javax.annotation.Nullable BigDecimal body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterNumberSerializeValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterStringSerialize + * @param body Input string as post body (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 Output string -
+ */ + public okhttp3.Call fakeOuterStringSerializeCall(@javax.annotation.Nullable String body, 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 = body; + + // create path and map variables + String localVarPath = "/fake/outer/string"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterStringSerializeValidateBeforeCall(@javax.annotation.Nullable String body, final ApiCallback _callback) throws ApiException { + return fakeOuterStringSerializeCall(body, _callback); + + } + + /** + * + * Test serialization of outer string types + * @param body Input string as post body (optional) + * @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 Output string -
+ */ + public String fakeOuterStringSerialize(@javax.annotation.Nullable String body) throws ApiException { + ApiResponse localVarResp = fakeOuterStringSerializeWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * + * Test serialization of outer string types + * @param body Input string as post body (optional) + * @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 Output string -
+ */ + public ApiResponse fakeOuterStringSerializeWithHttpInfo(@javax.annotation.Nullable String body) throws ApiException { + okhttp3.Call localVarCall = fakeOuterStringSerializeValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of outer string types + * @param body Input string as post body (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 Output string -
+ */ + public okhttp3.Call fakeOuterStringSerializeAsync(@javax.annotation.Nullable String body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterStringSerializeValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeRefParameter + * @param petId to test oneOf in parameter $ref (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 successful operation -
+ */ + public okhttp3.Call fakeRefParameterCall(@javax.annotation.Nonnull FakeRefParameterPetIdParameter petId, 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 = "/fake/pet/{petId}/reference/parameter" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeRefParameterValidateBeforeCall(@javax.annotation.Nonnull FakeRefParameterPetIdParameter petId, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling fakeRefParameter(Async)"); + } + + return fakeRefParameterCall(petId, _callback); + + } + + /** + * fake reference parameter + * + * @param petId to test oneOf in parameter $ref (required) + * @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 successful operation -
+ */ + public void fakeRefParameter(@javax.annotation.Nonnull FakeRefParameterPetIdParameter petId) throws ApiException { + fakeRefParameterWithHttpInfo(petId); + } + + /** + * fake reference parameter + * + * @param petId to test oneOf in parameter $ref (required) + * @return ApiResponse<Void> + * @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 successful operation -
+ */ + public ApiResponse fakeRefParameterWithHttpInfo(@javax.annotation.Nonnull FakeRefParameterPetIdParameter petId) throws ApiException { + okhttp3.Call localVarCall = fakeRefParameterValidateBeforeCall(petId, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * fake reference parameter (asynchronously) + * + * @param petId to test oneOf in parameter $ref (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 successful operation -
+ */ + public okhttp3.Call fakeRefParameterAsync(@javax.annotation.Nonnull FakeRefParameterPetIdParameter petId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeRefParameterValidateBeforeCall(petId, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for fakeRequiredNullableBodyGet + * @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 success -
+ */ + public okhttp3.Call fakeRequiredNullableBodyGetCall(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 = "/fake/required-nullable-body"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeRequiredNullableBodyGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return fakeRequiredNullableBodyGetCall(_callback); + + } + + /** + * fields in the response body, required and nullable are both true + * + * @return RequiredNullableBody + * @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 success -
+ */ + public RequiredNullableBody fakeRequiredNullableBodyGet() throws ApiException { + ApiResponse localVarResp = fakeRequiredNullableBodyGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * fields in the response body, required and nullable are both true + * + * @return ApiResponse<RequiredNullableBody> + * @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 success -
+ */ + public ApiResponse fakeRequiredNullableBodyGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fakeRequiredNullableBodyGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * fields in the response body, required and nullable are both true (asynchronously) + * + * @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 success -
+ */ + public okhttp3.Call fakeRequiredNullableBodyGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeRequiredNullableBodyGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeUploadRefRequestBodies + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (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 successful operation -
+ */ + public okhttp3.Call fakeUploadRefRequestBodiesCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, 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 = "/fake/pet/{petId}/uploadImage" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (additionalMetadata != null) { + localVarFormParams.put("additionalMetadata", additionalMetadata); + } + + if (_file != null) { + localVarFormParams.put("file", _file); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeUploadRefRequestBodiesValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling fakeUploadRefRequestBodies(Async)"); + } + + return fakeUploadRefRequestBodiesCall(petId, additionalMetadata, _file, _callback); + + } + + /** + * fake reference parameter + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (optional) + * @return ModelApiResponse + * @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 successful operation -
+ */ + public ModelApiResponse fakeUploadRefRequestBodies(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file) throws ApiException { + ApiResponse localVarResp = fakeUploadRefRequestBodiesWithHttpInfo(petId, additionalMetadata, _file); + return localVarResp.getData(); + } + + /** + * fake reference parameter + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @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 successful operation -
+ */ + public ApiResponse fakeUploadRefRequestBodiesWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file) throws ApiException { + okhttp3.Call localVarCall = fakeUploadRefRequestBodiesValidateBeforeCall(petId, additionalMetadata, _file, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * fake reference parameter (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (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 successful operation -
+ */ + public okhttp3.Call fakeUploadRefRequestBodiesAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeUploadRefRequestBodiesValidateBeforeCall(petId, additionalMetadata, _file, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getFakeArrayofenums + * @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 Got named array of enums -
+ */ + public okhttp3.Call getFakeArrayofenumsCall(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 = "/fake/array-of-enums"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getFakeArrayofenumsValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return getFakeArrayofenumsCall(_callback); + + } + + /** + * Array of Enums + * + * @return List<OuterEnum> + * @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 Got named array of enums -
+ */ + public List getFakeArrayofenums() throws ApiException { + ApiResponse> localVarResp = getFakeArrayofenumsWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Array of Enums + * + * @return ApiResponse<List<OuterEnum>> + * @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 Got named array of enums -
+ */ + public ApiResponse> getFakeArrayofenumsWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getFakeArrayofenumsValidateBeforeCall(null); + Type localVarReturnType = new TypeToken>(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Array of Enums (asynchronously) + * + * @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 Got named array of enums -
+ */ + public okhttp3.Call getFakeArrayofenumsAsync(final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = getFakeArrayofenumsValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getFakeHealth + * @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 The instance started successfully -
+ */ + public okhttp3.Call getFakeHealthCall(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 = "/fake/health"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getFakeHealthValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return getFakeHealthCall(_callback); + + } + + /** + * Health check endpoint + * + * @return HealthCheckResult + * @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 The instance started successfully -
+ */ + public HealthCheckResult getFakeHealth() throws ApiException { + ApiResponse localVarResp = getFakeHealthWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Health check endpoint + * + * @return ApiResponse<HealthCheckResult> + * @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 The instance started successfully -
+ */ + public ApiResponse getFakeHealthWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getFakeHealthValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Health check endpoint (asynchronously) + * + * @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 The instance started successfully -
+ */ + public okhttp3.Call getFakeHealthAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getFakeHealthValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getParameterNameMapping + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (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 getParameterNameMappingCall(@javax.annotation.Nonnull Long underscoreType, @javax.annotation.Nonnull String type, @javax.annotation.Nonnull String typeWithUnderscore, 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 = "/fake/parameter-name-mapping"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (type != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("type", type)); + } + + final String[] localVarAccepts = { + }; + 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); + } + + if (underscoreType != null) { + localVarHeaderParams.put("_type", localVarApiClient.parameterToString(underscoreType)); + } + + + if (typeWithUnderscore != null) { + localVarHeaderParams.put("type_", localVarApiClient.parameterToString(typeWithUnderscore)); + } + + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getParameterNameMappingValidateBeforeCall(@javax.annotation.Nonnull Long underscoreType, @javax.annotation.Nonnull String type, @javax.annotation.Nonnull String typeWithUnderscore, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'underscoreType' is set + if (underscoreType == null) { + throw new ApiException("Missing the required parameter 'underscoreType' when calling getParameterNameMapping(Async)"); + } + + // verify the required parameter 'type' is set + if (type == null) { + throw new ApiException("Missing the required parameter 'type' when calling getParameterNameMapping(Async)"); + } + + // verify the required parameter 'typeWithUnderscore' is set + if (typeWithUnderscore == null) { + throw new ApiException("Missing the required parameter 'typeWithUnderscore' when calling getParameterNameMapping(Async)"); + } + + return getParameterNameMappingCall(underscoreType, type, typeWithUnderscore, _callback); + + } + + /** + * parameter name mapping test + * + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (required) + * @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 void getParameterNameMapping(@javax.annotation.Nonnull Long underscoreType, @javax.annotation.Nonnull String type, @javax.annotation.Nonnull String typeWithUnderscore) throws ApiException { + getParameterNameMappingWithHttpInfo(underscoreType, type, typeWithUnderscore); + } + + /** + * parameter name mapping test + * + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (required) + * @return ApiResponse<Void> + * @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 getParameterNameMappingWithHttpInfo(@javax.annotation.Nonnull Long underscoreType, @javax.annotation.Nonnull String type, @javax.annotation.Nonnull String typeWithUnderscore) throws ApiException { + okhttp3.Call localVarCall = getParameterNameMappingValidateBeforeCall(underscoreType, type, typeWithUnderscore, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * parameter name mapping test (asynchronously) + * + * @param underscoreType _type (required) + * @param type type (required) + * @param typeWithUnderscore type_ (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 getParameterNameMappingAsync(@javax.annotation.Nonnull Long underscoreType, @javax.annotation.Nonnull String type, @javax.annotation.Nonnull String typeWithUnderscore, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getParameterNameMappingValidateBeforeCall(underscoreType, type, typeWithUnderscore, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testAdditionalPropertiesReference + * @param requestBody request body (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 successful operation -
+ */ + public okhttp3.Call testAdditionalPropertiesReferenceCall(@javax.annotation.Nonnull Map requestBody, 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 = requestBody; + + // create path and map variables + String localVarPath = "/fake/additionalProperties-reference"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testAdditionalPropertiesReferenceValidateBeforeCall(@javax.annotation.Nonnull Map requestBody, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference(Async)"); + } + + return testAdditionalPropertiesReferenceCall(requestBody, _callback); + + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @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 successful operation -
+ */ + public void testAdditionalPropertiesReference(@javax.annotation.Nonnull Map requestBody) throws ApiException { + testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @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 successful operation -
+ */ + public ApiResponse testAdditionalPropertiesReferenceWithHttpInfo(@javax.annotation.Nonnull Map requestBody) throws ApiException { + okhttp3.Call localVarCall = testAdditionalPropertiesReferenceValidateBeforeCall(requestBody, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test referenced additionalProperties (asynchronously) + * + * @param requestBody request body (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 successful operation -
+ */ + public okhttp3.Call testAdditionalPropertiesReferenceAsync(@javax.annotation.Nonnull Map requestBody, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testAdditionalPropertiesReferenceValidateBeforeCall(requestBody, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testBodyWithFileSchema + * @param fileSchemaTestClass (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 Success -
+ */ + public okhttp3.Call testBodyWithFileSchemaCall(@javax.annotation.Nonnull FileSchemaTestClass fileSchemaTestClass, 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 = fileSchemaTestClass; + + // create path and map variables + String localVarPath = "/fake/body-with-file-schema"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testBodyWithFileSchemaValidateBeforeCall(@javax.annotation.Nonnull FileSchemaTestClass fileSchemaTestClass, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'fileSchemaTestClass' is set + if (fileSchemaTestClass == null) { + throw new ApiException("Missing the required parameter 'fileSchemaTestClass' when calling testBodyWithFileSchema(Async)"); + } + + return testBodyWithFileSchemaCall(fileSchemaTestClass, _callback); + + } + + /** + * + * For this test, the body for this request much reference a schema named `File`. + * @param fileSchemaTestClass (required) + * @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 Success -
+ */ + public void testBodyWithFileSchema(@javax.annotation.Nonnull FileSchemaTestClass fileSchemaTestClass) throws ApiException { + testBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); + } + + /** + * + * For this test, the body for this request much reference a schema named `File`. + * @param fileSchemaTestClass (required) + * @return ApiResponse<Void> + * @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 Success -
+ */ + public ApiResponse testBodyWithFileSchemaWithHttpInfo(@javax.annotation.Nonnull FileSchemaTestClass fileSchemaTestClass) throws ApiException { + okhttp3.Call localVarCall = testBodyWithFileSchemaValidateBeforeCall(fileSchemaTestClass, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * For this test, the body for this request much reference a schema named `File`. + * @param fileSchemaTestClass (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 Success -
+ */ + public okhttp3.Call testBodyWithFileSchemaAsync(@javax.annotation.Nonnull FileSchemaTestClass fileSchemaTestClass, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testBodyWithFileSchemaValidateBeforeCall(fileSchemaTestClass, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testBodyWithQueryParams + * @param query (required) + * @param user (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 Success -
+ */ + public okhttp3.Call testBodyWithQueryParamsCall(@javax.annotation.Nonnull String query, @javax.annotation.Nonnull User user, 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 = user; + + // create path and map variables + String localVarPath = "/fake/body-with-query-params"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (query != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("query", query)); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testBodyWithQueryParamsValidateBeforeCall(@javax.annotation.Nonnull String query, @javax.annotation.Nonnull User user, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'query' is set + if (query == null) { + throw new ApiException("Missing the required parameter 'query' when calling testBodyWithQueryParams(Async)"); + } + + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling testBodyWithQueryParams(Async)"); + } + + return testBodyWithQueryParamsCall(query, user, _callback); + + } + + /** + * + * + * @param query (required) + * @param user (required) + * @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 Success -
+ */ + public void testBodyWithQueryParams(@javax.annotation.Nonnull String query, @javax.annotation.Nonnull User user) throws ApiException { + testBodyWithQueryParamsWithHttpInfo(query, user); + } + + /** + * + * + * @param query (required) + * @param user (required) + * @return ApiResponse<Void> + * @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 Success -
+ */ + public ApiResponse testBodyWithQueryParamsWithHttpInfo(@javax.annotation.Nonnull String query, @javax.annotation.Nonnull User user) throws ApiException { + okhttp3.Call localVarCall = testBodyWithQueryParamsValidateBeforeCall(query, user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * + * @param query (required) + * @param user (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 Success -
+ */ + public okhttp3.Call testBodyWithQueryParamsAsync(@javax.annotation.Nonnull String query, @javax.annotation.Nonnull User user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testBodyWithQueryParamsValidateBeforeCall(query, user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testClientModel + * @param client client model (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 successful operation -
+ */ + public okhttp3.Call testClientModelCall(@javax.annotation.Nonnull Client client, 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 = client; + + // create path and map variables + String localVarPath = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testClientModelValidateBeforeCall(@javax.annotation.Nonnull Client client, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'client' is set + if (client == null) { + throw new ApiException("Missing the required parameter 'client' when calling testClientModel(Async)"); + } + + return testClientModelCall(client, _callback); + + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param client client model (required) + * @return Client + * @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 successful operation -
+ */ + public Client testClientModel(@javax.annotation.Nonnull Client client) throws ApiException { + ApiResponse localVarResp = testClientModelWithHttpInfo(client); + return localVarResp.getData(); + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param client client model (required) + * @return ApiResponse<Client> + * @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 successful operation -
+ */ + public ApiResponse testClientModelWithHttpInfo(@javax.annotation.Nonnull Client client) throws ApiException { + okhttp3.Call localVarCall = testClientModelValidateBeforeCall(client, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * To test \"client\" model (asynchronously) + * To test \"client\" model + * @param client client model (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 successful operation -
+ */ + public okhttp3.Call testClientModelAsync(@javax.annotation.Nonnull Client client, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testClientModelValidateBeforeCall(client, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for testEndpointParameters + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional, default to 2010-02-01T10:20:10.111110+01:00) + * @param password None (optional) + * @param paramCallback None (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
400 Invalid username supplied -
404 User not found -
+ */ + public okhttp3.Call testEndpointParametersCall(@javax.annotation.Nonnull BigDecimal number, @javax.annotation.Nonnull Double _double, @javax.annotation.Nonnull String patternWithoutDelimiter, @javax.annotation.Nonnull byte[] _byte, @javax.annotation.Nullable Integer integer, @javax.annotation.Nullable Integer int32, @javax.annotation.Nullable Long int64, @javax.annotation.Nullable Float _float, @javax.annotation.Nullable String string, @javax.annotation.Nullable File binary, @javax.annotation.Nullable LocalDate date, @javax.annotation.Nullable OffsetDateTime dateTime, @javax.annotation.Nullable String password, @javax.annotation.Nullable String paramCallback, 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 = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (integer != null) { + localVarFormParams.put("integer", integer); + } + + if (int32 != null) { + localVarFormParams.put("int32", int32); + } + + if (int64 != null) { + localVarFormParams.put("int64", int64); + } + + if (number != null) { + localVarFormParams.put("number", number); + } + + if (_float != null) { + localVarFormParams.put("float", _float); + } + + if (_double != null) { + localVarFormParams.put("double", _double); + } + + if (string != null) { + localVarFormParams.put("string", string); + } + + if (patternWithoutDelimiter != null) { + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); + } + + if (_byte != null) { + localVarFormParams.put("byte", _byte); + } + + if (binary != null) { + localVarFormParams.put("binary", binary); + } + + if (date != null) { + localVarFormParams.put("date", date); + } + + if (dateTime != null) { + localVarFormParams.put("dateTime", dateTime); + } + + if (password != null) { + localVarFormParams.put("password", password); + } + + if (paramCallback != null) { + localVarFormParams.put("callback", paramCallback); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testEndpointParametersValidateBeforeCall(@javax.annotation.Nonnull BigDecimal number, @javax.annotation.Nonnull Double _double, @javax.annotation.Nonnull String patternWithoutDelimiter, @javax.annotation.Nonnull byte[] _byte, @javax.annotation.Nullable Integer integer, @javax.annotation.Nullable Integer int32, @javax.annotation.Nullable Long int64, @javax.annotation.Nullable Float _float, @javax.annotation.Nullable String string, @javax.annotation.Nullable File binary, @javax.annotation.Nullable LocalDate date, @javax.annotation.Nullable OffsetDateTime dateTime, @javax.annotation.Nullable String password, @javax.annotation.Nullable String paramCallback, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + return testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, _callback); + + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional, default to 2010-02-01T10:20:10.111110+01:00) + * @param password None (optional) + * @param paramCallback None (optional) + * @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
400 Invalid username supplied -
404 User not found -
+ */ + public void testEndpointParameters(@javax.annotation.Nonnull BigDecimal number, @javax.annotation.Nonnull Double _double, @javax.annotation.Nonnull String patternWithoutDelimiter, @javax.annotation.Nonnull byte[] _byte, @javax.annotation.Nullable Integer integer, @javax.annotation.Nullable Integer int32, @javax.annotation.Nullable Long int64, @javax.annotation.Nullable Float _float, @javax.annotation.Nullable String string, @javax.annotation.Nullable File binary, @javax.annotation.Nullable LocalDate date, @javax.annotation.Nullable OffsetDateTime dateTime, @javax.annotation.Nullable String password, @javax.annotation.Nullable String paramCallback) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional, default to 2010-02-01T10:20:10.111110+01:00) + * @param password None (optional) + * @param paramCallback None (optional) + * @return ApiResponse<Void> + * @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
400 Invalid username supplied -
404 User not found -
+ */ + public ApiResponse testEndpointParametersWithHttpInfo(@javax.annotation.Nonnull BigDecimal number, @javax.annotation.Nonnull Double _double, @javax.annotation.Nonnull String patternWithoutDelimiter, @javax.annotation.Nonnull byte[] _byte, @javax.annotation.Nullable Integer integer, @javax.annotation.Nullable Integer int32, @javax.annotation.Nullable Long int64, @javax.annotation.Nullable Float _float, @javax.annotation.Nullable String string, @javax.annotation.Nullable File binary, @javax.annotation.Nullable LocalDate date, @javax.annotation.Nullable OffsetDateTime dateTime, @javax.annotation.Nullable String password, @javax.annotation.Nullable String paramCallback) throws ApiException { + okhttp3.Call localVarCall = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * @param number None (required) + * @param _double None (required) + * @param patternWithoutDelimiter None (required) + * @param _byte None (required) + * @param integer None (optional) + * @param int32 None (optional) + * @param int64 None (optional) + * @param _float None (optional) + * @param string None (optional) + * @param binary None (optional) + * @param date None (optional) + * @param dateTime None (optional, default to 2010-02-01T10:20:10.111110+01:00) + * @param password None (optional) + * @param paramCallback None (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
400 Invalid username supplied -
404 User not found -
+ */ + public okhttp3.Call testEndpointParametersAsync(@javax.annotation.Nonnull BigDecimal number, @javax.annotation.Nonnull Double _double, @javax.annotation.Nonnull String patternWithoutDelimiter, @javax.annotation.Nonnull byte[] _byte, @javax.annotation.Nullable Integer integer, @javax.annotation.Nullable Integer int32, @javax.annotation.Nullable Long int64, @javax.annotation.Nullable Float _float, @javax.annotation.Nullable String string, @javax.annotation.Nullable File binary, @javax.annotation.Nullable LocalDate date, @javax.annotation.Nullable OffsetDateTime dateTime, @javax.annotation.Nullable String password, @javax.annotation.Nullable String paramCallback, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testEnumParameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @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
400 Invalid request -
404 Not found -
+ */ + public okhttp3.Call testEnumParametersCall(@javax.annotation.Nullable List enumHeaderStringArray, @javax.annotation.Nullable String enumHeaderString, @javax.annotation.Nullable List enumQueryStringArray, @javax.annotation.Nullable String enumQueryString, @javax.annotation.Nullable Integer enumQueryInteger, @javax.annotation.Nullable Double enumQueryDouble, @javax.annotation.Nullable List enumFormStringArray, @javax.annotation.Nullable String enumFormString, 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 = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (enumFormStringArray != null) { + localVarFormParams.put("enum_form_string_array", enumFormStringArray); + } + + if (enumFormString != null) { + localVarFormParams.put("enum_form_string", enumFormString); + } + + if (enumQueryStringArray != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "enum_query_string_array", enumQueryStringArray)); + } + + if (enumQueryString != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("enum_query_string", enumQueryString)); + } + + if (enumQueryInteger != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("enum_query_integer", enumQueryInteger)); + } + + if (enumQueryDouble != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("enum_query_double", enumQueryDouble)); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + if (enumHeaderStringArray != null) { + localVarHeaderParams.put("enum_header_string_array", localVarApiClient.parameterToString(enumHeaderStringArray)); + } + + + if (enumHeaderString != null) { + localVarHeaderParams.put("enum_header_string", localVarApiClient.parameterToString(enumHeaderString)); + } + + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testEnumParametersValidateBeforeCall(@javax.annotation.Nullable List enumHeaderStringArray, @javax.annotation.Nullable String enumHeaderString, @javax.annotation.Nullable List enumQueryStringArray, @javax.annotation.Nullable String enumQueryString, @javax.annotation.Nullable Integer enumQueryInteger, @javax.annotation.Nullable Double enumQueryDouble, @javax.annotation.Nullable List enumFormStringArray, @javax.annotation.Nullable String enumFormString, final ApiCallback _callback) throws ApiException { + return testEnumParametersCall(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, _callback); + + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @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
400 Invalid request -
404 Not found -
+ */ + public void testEnumParameters(@javax.annotation.Nullable List enumHeaderStringArray, @javax.annotation.Nullable String enumHeaderString, @javax.annotation.Nullable List enumQueryStringArray, @javax.annotation.Nullable String enumQueryString, @javax.annotation.Nullable Integer enumQueryInteger, @javax.annotation.Nullable Double enumQueryDouble, @javax.annotation.Nullable List enumFormStringArray, @javax.annotation.Nullable String enumFormString) throws ApiException { + testEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @return ApiResponse<Void> + * @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
400 Invalid request -
404 Not found -
+ */ + public ApiResponse testEnumParametersWithHttpInfo(@javax.annotation.Nullable List enumHeaderStringArray, @javax.annotation.Nullable String enumHeaderString, @javax.annotation.Nullable List enumQueryStringArray, @javax.annotation.Nullable String enumQueryString, @javax.annotation.Nullable Integer enumQueryInteger, @javax.annotation.Nullable Double enumQueryDouble, @javax.annotation.Nullable List enumFormStringArray, @javax.annotation.Nullable String enumFormString) throws ApiException { + okhttp3.Call localVarCall = testEnumParametersValidateBeforeCall(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * To test enum parameters (asynchronously) + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) + * @param enumQueryInteger Query parameter enum test (double) (optional) + * @param enumQueryDouble Query parameter enum test (double) (optional) + * @param enumFormStringArray Form parameter enum test (string array) (optional) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @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
400 Invalid request -
404 Not found -
+ */ + public okhttp3.Call testEnumParametersAsync(@javax.annotation.Nullable List enumHeaderStringArray, @javax.annotation.Nullable String enumHeaderString, @javax.annotation.Nullable List enumQueryStringArray, @javax.annotation.Nullable String enumQueryString, @javax.annotation.Nullable Integer enumQueryInteger, @javax.annotation.Nullable Double enumQueryDouble, @javax.annotation.Nullable List enumFormStringArray, @javax.annotation.Nullable String enumFormString, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testEnumParametersValidateBeforeCall(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + private okhttp3.Call testGroupParametersCall(@javax.annotation.Nonnull Integer requiredStringGroup, @javax.annotation.Nonnull Boolean requiredBooleanGroup, @javax.annotation.Nonnull Long requiredInt64Group, @javax.annotation.Nullable Integer stringGroup, @javax.annotation.Nullable Boolean booleanGroup, @javax.annotation.Nullable Long int64Group, 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 = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (requiredStringGroup != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("required_string_group", requiredStringGroup)); + } + + if (requiredInt64Group != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("required_int64_group", requiredInt64Group)); + } + + if (stringGroup != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("string_group", stringGroup)); + } + + if (int64Group != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("int64_group", int64Group)); + } + + final String[] localVarAccepts = { + }; + 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); + } + + if (requiredBooleanGroup != null) { + localVarHeaderParams.put("required_boolean_group", localVarApiClient.parameterToString(requiredBooleanGroup)); + } + + + if (booleanGroup != null) { + localVarHeaderParams.put("boolean_group", localVarApiClient.parameterToString(booleanGroup)); + } + + + String[] localVarAuthNames = new String[] { "bearer_test" }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testGroupParametersValidateBeforeCall(@javax.annotation.Nonnull Integer requiredStringGroup, @javax.annotation.Nonnull Boolean requiredBooleanGroup, @javax.annotation.Nonnull Long requiredInt64Group, @javax.annotation.Nullable Integer stringGroup, @javax.annotation.Nullable Boolean booleanGroup, @javax.annotation.Nullable Long int64Group, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'requiredStringGroup' is set + if (requiredStringGroup == null) { + throw new ApiException("Missing the required parameter 'requiredStringGroup' when calling testGroupParameters(Async)"); + } + + // verify the required parameter 'requiredBooleanGroup' is set + if (requiredBooleanGroup == null) { + throw new ApiException("Missing the required parameter 'requiredBooleanGroup' when calling testGroupParameters(Async)"); + } + + // verify the required parameter 'requiredInt64Group' is set + if (requiredInt64Group == null) { + throw new ApiException("Missing the required parameter 'requiredInt64Group' when calling testGroupParameters(Async)"); + } + + return testGroupParametersCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + + } + + + private ApiResponse testGroupParametersWithHttpInfo(@javax.annotation.Nonnull Integer requiredStringGroup, @javax.annotation.Nonnull Boolean requiredBooleanGroup, @javax.annotation.Nonnull Long requiredInt64Group, @javax.annotation.Nullable Integer stringGroup, @javax.annotation.Nullable Boolean booleanGroup, @javax.annotation.Nullable Long int64Group) throws ApiException { + okhttp3.Call localVarCall = testGroupParametersValidateBeforeCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, null); + return localVarApiClient.execute(localVarCall); + } + + private okhttp3.Call testGroupParametersAsync(@javax.annotation.Nonnull Integer requiredStringGroup, @javax.annotation.Nonnull Boolean requiredBooleanGroup, @javax.annotation.Nonnull Long requiredInt64Group, @javax.annotation.Nullable Integer stringGroup, @javax.annotation.Nullable Boolean booleanGroup, @javax.annotation.Nullable Long int64Group, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testGroupParametersValidateBeforeCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + + public class APItestGroupParametersRequest { + @javax.annotation.Nonnull + private final Integer requiredStringGroup; + @javax.annotation.Nonnull + private final Boolean requiredBooleanGroup; + @javax.annotation.Nonnull + private final Long requiredInt64Group; + @javax.annotation.Nullable + private Integer stringGroup; + @javax.annotation.Nullable + private Boolean booleanGroup; + @javax.annotation.Nullable + private Long int64Group; + + private APItestGroupParametersRequest(@javax.annotation.Nonnull Integer requiredStringGroup, @javax.annotation.Nonnull Boolean requiredBooleanGroup, @javax.annotation.Nonnull Long requiredInt64Group) { + this.requiredStringGroup = requiredStringGroup; + this.requiredBooleanGroup = requiredBooleanGroup; + this.requiredInt64Group = requiredInt64Group; + } + + /** + * Set stringGroup + * @param stringGroup String in group parameters (optional) + * @return APItestGroupParametersRequest + */ + public APItestGroupParametersRequest stringGroup(@javax.annotation.Nullable Integer stringGroup) { + this.stringGroup = stringGroup; + return this; + } + + /** + * Set booleanGroup + * @param booleanGroup Boolean in group parameters (optional) + * @return APItestGroupParametersRequest + */ + public APItestGroupParametersRequest booleanGroup(@javax.annotation.Nullable Boolean booleanGroup) { + this.booleanGroup = booleanGroup; + return this; + } + + /** + * Set int64Group + * @param int64Group Integer in group parameters (optional) + * @return APItestGroupParametersRequest + */ + public APItestGroupParametersRequest int64Group(@javax.annotation.Nullable Long int64Group) { + this.int64Group = int64Group; + return this; + } + + /** + * Build call for testGroupParameters + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
400 Something wrong -
+ */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return testGroupParametersCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + } + + /** + * Execute testGroupParameters request + * @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
400 Something wrong -
+ */ + public void execute() throws ApiException { + testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /** + * Execute testGroupParameters request with HTTP info returned + * @return ApiResponse<Void> + * @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
400 Something wrong -
+ */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /** + * Execute testGroupParameters request (asynchronously) + * @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
400 Something wrong -
+ */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return testGroupParametersAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + } + } + + /** + * Fake endpoint to test group parameters (optional) + * Fake endpoint to test group parameters (optional) + * @param requiredStringGroup Required String in group parameters (required) + * @param requiredBooleanGroup Required Boolean in group parameters (required) + * @param requiredInt64Group Required Integer in group parameters (required) + * @return APItestGroupParametersRequest + * @http.response.details + + + + +
Response Details
Status Code Description Response Headers
400 Something wrong -
+ */ + public APItestGroupParametersRequest testGroupParameters(@javax.annotation.Nonnull Integer requiredStringGroup, @javax.annotation.Nonnull Boolean requiredBooleanGroup, @javax.annotation.Nonnull Long requiredInt64Group) { + return new APItestGroupParametersRequest(requiredStringGroup, requiredBooleanGroup, requiredInt64Group); + } + /** + * Build call for testInlineAdditionalProperties + * @param requestBody request body (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 successful operation -
+ */ + public okhttp3.Call testInlineAdditionalPropertiesCall(@javax.annotation.Nonnull Map requestBody, 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 = requestBody; + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testInlineAdditionalPropertiesValidateBeforeCall(@javax.annotation.Nonnull Map requestBody, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException("Missing the required parameter 'requestBody' when calling testInlineAdditionalProperties(Async)"); + } + + return testInlineAdditionalPropertiesCall(requestBody, _callback); + + } + + /** + * test inline additionalProperties + * + * @param requestBody request body (required) + * @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 successful operation -
+ */ + public void testInlineAdditionalProperties(@javax.annotation.Nonnull Map requestBody) throws ApiException { + testInlineAdditionalPropertiesWithHttpInfo(requestBody); + } + + /** + * test inline additionalProperties + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @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 successful operation -
+ */ + public ApiResponse testInlineAdditionalPropertiesWithHttpInfo(@javax.annotation.Nonnull Map requestBody) throws ApiException { + okhttp3.Call localVarCall = testInlineAdditionalPropertiesValidateBeforeCall(requestBody, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test inline additionalProperties (asynchronously) + * + * @param requestBody request body (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 successful operation -
+ */ + public okhttp3.Call testInlineAdditionalPropertiesAsync(@javax.annotation.Nonnull Map requestBody, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testInlineAdditionalPropertiesValidateBeforeCall(requestBody, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testInlineFreeformAdditionalProperties + * @param testInlineFreeformAdditionalPropertiesRequest request body (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 successful operation -
+ */ + public okhttp3.Call testInlineFreeformAdditionalPropertiesCall(@javax.annotation.Nonnull TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest, 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 = testInlineFreeformAdditionalPropertiesRequest; + + // create path and map variables + String localVarPath = "/fake/inline-freeform-additionalProperties"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testInlineFreeformAdditionalPropertiesValidateBeforeCall(@javax.annotation.Nonnull TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'testInlineFreeformAdditionalPropertiesRequest' is set + if (testInlineFreeformAdditionalPropertiesRequest == null) { + throw new ApiException("Missing the required parameter 'testInlineFreeformAdditionalPropertiesRequest' when calling testInlineFreeformAdditionalProperties(Async)"); + } + + return testInlineFreeformAdditionalPropertiesCall(testInlineFreeformAdditionalPropertiesRequest, _callback); + + } + + /** + * test inline free-form additionalProperties + * + * @param testInlineFreeformAdditionalPropertiesRequest request body (required) + * @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 successful operation -
+ */ + public void testInlineFreeformAdditionalProperties(@javax.annotation.Nonnull TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest) throws ApiException { + testInlineFreeformAdditionalPropertiesWithHttpInfo(testInlineFreeformAdditionalPropertiesRequest); + } + + /** + * test inline free-form additionalProperties + * + * @param testInlineFreeformAdditionalPropertiesRequest request body (required) + * @return ApiResponse<Void> + * @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 successful operation -
+ */ + public ApiResponse testInlineFreeformAdditionalPropertiesWithHttpInfo(@javax.annotation.Nonnull TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest) throws ApiException { + okhttp3.Call localVarCall = testInlineFreeformAdditionalPropertiesValidateBeforeCall(testInlineFreeformAdditionalPropertiesRequest, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test inline free-form additionalProperties (asynchronously) + * + * @param testInlineFreeformAdditionalPropertiesRequest request body (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 successful operation -
+ */ + public okhttp3.Call testInlineFreeformAdditionalPropertiesAsync(@javax.annotation.Nonnull TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testInlineFreeformAdditionalPropertiesValidateBeforeCall(testInlineFreeformAdditionalPropertiesRequest, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testJsonFormData + * @param param field1 (required) + * @param param2 field2 (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 successful operation -
+ */ + public okhttp3.Call testJsonFormDataCall(@javax.annotation.Nonnull String param, @javax.annotation.Nonnull String param2, 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 = "/fake/jsonFormData"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (param != null) { + localVarFormParams.put("param", param); + } + + if (param2 != null) { + localVarFormParams.put("param2", param2); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testJsonFormDataValidateBeforeCall(@javax.annotation.Nonnull String param, @javax.annotation.Nonnull String param2, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException("Missing the required parameter 'param' when calling testJsonFormData(Async)"); + } + + // verify the required parameter 'param2' is set + if (param2 == null) { + throw new ApiException("Missing the required parameter 'param2' when calling testJsonFormData(Async)"); + } + + return testJsonFormDataCall(param, param2, _callback); + + } + + /** + * test json serialization of form data + * + * @param param field1 (required) + * @param param2 field2 (required) + * @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 successful operation -
+ */ + public void testJsonFormData(@javax.annotation.Nonnull String param, @javax.annotation.Nonnull String param2) throws ApiException { + testJsonFormDataWithHttpInfo(param, param2); + } + + /** + * test json serialization of form data + * + * @param param field1 (required) + * @param param2 field2 (required) + * @return ApiResponse<Void> + * @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 successful operation -
+ */ + public ApiResponse testJsonFormDataWithHttpInfo(@javax.annotation.Nonnull String param, @javax.annotation.Nonnull String param2) throws ApiException { + okhttp3.Call localVarCall = testJsonFormDataValidateBeforeCall(param, param2, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test json serialization of form data (asynchronously) + * + * @param param field1 (required) + * @param param2 field2 (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 successful operation -
+ */ + public okhttp3.Call testJsonFormDataAsync(@javax.annotation.Nonnull String param, @javax.annotation.Nonnull String param2, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testJsonFormDataValidateBeforeCall(param, param2, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testNullableRequiredFieldsAnyOf + * @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 successful operation -
+ */ + public okhttp3.Call testNullableRequiredFieldsAnyOfCall(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 = "/fake/nullable-required-fields-anyof"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testNullableRequiredFieldsAnyOfValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return testNullableRequiredFieldsAnyOfCall(_callback); + + } + + /** + * test anyOf with map of objects containing nullable required fields + * Tests that anyOf deserialization works when object values contain required fields that are nullable (e.g. Record<string, { before: string | null, after: string | null }>) + * @return NullableFieldsMapResponse + * @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 successful operation -
+ */ + public NullableFieldsMapResponse testNullableRequiredFieldsAnyOf() throws ApiException { + ApiResponse localVarResp = testNullableRequiredFieldsAnyOfWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * test anyOf with map of objects containing nullable required fields + * Tests that anyOf deserialization works when object values contain required fields that are nullable (e.g. Record<string, { before: string | null, after: string | null }>) + * @return ApiResponse<NullableFieldsMapResponse> + * @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 successful operation -
+ */ + public ApiResponse testNullableRequiredFieldsAnyOfWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = testNullableRequiredFieldsAnyOfValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * test anyOf with map of objects containing nullable required fields (asynchronously) + * Tests that anyOf deserialization works when object values contain required fields that are nullable (e.g. Record<string, { before: string | null, after: string | null }>) + * @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 successful operation -
+ */ + public okhttp3.Call testNullableRequiredFieldsAnyOfAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testNullableRequiredFieldsAnyOfValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for testQueryParameterCollectionFormat + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (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 Success -
+ */ + public okhttp3.Call testQueryParameterCollectionFormatCall(@javax.annotation.Nonnull List pipe, @javax.annotation.Nonnull List ioutil, @javax.annotation.Nonnull List http, @javax.annotation.Nonnull List url, @javax.annotation.Nonnull List context, 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 = "/fake/test-query-parameters"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (pipe != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "pipe", pipe)); + } + + if (ioutil != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "ioutil", ioutil)); + } + + if (http != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("ssv", "http", http)); + } + + if (url != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "url", url)); + } + + if (context != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "context", context)); + } + + final String[] localVarAccepts = { + }; + 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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testQueryParameterCollectionFormatValidateBeforeCall(@javax.annotation.Nonnull List pipe, @javax.annotation.Nonnull List ioutil, @javax.annotation.Nonnull List http, @javax.annotation.Nonnull List url, @javax.annotation.Nonnull List context, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'pipe' is set + if (pipe == null) { + throw new ApiException("Missing the required parameter 'pipe' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'ioutil' is set + if (ioutil == null) { + throw new ApiException("Missing the required parameter 'ioutil' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'http' is set + if (http == null) { + throw new ApiException("Missing the required parameter 'http' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'url' is set + if (url == null) { + throw new ApiException("Missing the required parameter 'url' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'context' is set + if (context == null) { + throw new ApiException("Missing the required parameter 'context' when calling testQueryParameterCollectionFormat(Async)"); + } + + return testQueryParameterCollectionFormatCall(pipe, ioutil, http, url, context, _callback); + + } + + /** + * + * To test the collection format in query parameters + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @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 Success -
+ */ + public void testQueryParameterCollectionFormat(@javax.annotation.Nonnull List pipe, @javax.annotation.Nonnull List ioutil, @javax.annotation.Nonnull List http, @javax.annotation.Nonnull List url, @javax.annotation.Nonnull List context) throws ApiException { + testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); + } + + /** + * + * To test the collection format in query parameters + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @return ApiResponse<Void> + * @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 Success -
+ */ + public ApiResponse testQueryParameterCollectionFormatWithHttpInfo(@javax.annotation.Nonnull List pipe, @javax.annotation.Nonnull List ioutil, @javax.annotation.Nonnull List http, @javax.annotation.Nonnull List url, @javax.annotation.Nonnull List context) throws ApiException { + okhttp3.Call localVarCall = testQueryParameterCollectionFormatValidateBeforeCall(pipe, ioutil, http, url, context, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * To test the collection format in query parameters + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (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 Success -
+ */ + public okhttp3.Call testQueryParameterCollectionFormatAsync(@javax.annotation.Nonnull List pipe, @javax.annotation.Nonnull List ioutil, @javax.annotation.Nonnull List http, @javax.annotation.Nonnull List url, @javax.annotation.Nonnull List context, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testQueryParameterCollectionFormatValidateBeforeCall(pipe, ioutil, http, url, context, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testStringMapReference + * @param requestBody request body (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 successful operation -
+ */ + public okhttp3.Call testStringMapReferenceCall(@javax.annotation.Nonnull Map requestBody, 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 = requestBody; + + // create path and map variables + String localVarPath = "/fake/stringMap-reference"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testStringMapReferenceValidateBeforeCall(@javax.annotation.Nonnull Map requestBody, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException("Missing the required parameter 'requestBody' when calling testStringMapReference(Async)"); + } + + return testStringMapReferenceCall(requestBody, _callback); + + } + + /** + * test referenced string map + * + * @param requestBody request body (required) + * @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 successful operation -
+ */ + public void testStringMapReference(@javax.annotation.Nonnull Map requestBody) throws ApiException { + testStringMapReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced string map + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @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 successful operation -
+ */ + public ApiResponse testStringMapReferenceWithHttpInfo(@javax.annotation.Nonnull Map requestBody) throws ApiException { + okhttp3.Call localVarCall = testStringMapReferenceValidateBeforeCall(requestBody, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test referenced string map (asynchronously) + * + * @param requestBody request body (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 successful operation -
+ */ + public okhttp3.Call testStringMapReferenceAsync(@javax.annotation.Nonnull Map requestBody, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testStringMapReferenceValidateBeforeCall(requestBody, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java new file mode 100644 index 000000000000..97108fb36ace --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -0,0 +1,201 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import org.openapitools.client.model.Client; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeClassnameTags123Api { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public FakeClassnameTags123Api() { + this(Configuration.getDefaultApiClient()); + } + + public FakeClassnameTags123Api(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for testClassname + * @param client client model (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 successful operation -
+ */ + public okhttp3.Call testClassnameCall(@javax.annotation.Nonnull Client client, 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 = client; + + // create path and map variables + String localVarPath = "/fake_classname_test"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "api_key_query" }; + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testClassnameValidateBeforeCall(@javax.annotation.Nonnull Client client, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'client' is set + if (client == null) { + throw new ApiException("Missing the required parameter 'client' when calling testClassname(Async)"); + } + + return testClassnameCall(client, _callback); + + } + + /** + * To test class name in snake case + * To test class name in snake case + * @param client client model (required) + * @return Client + * @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 successful operation -
+ */ + public Client testClassname(@javax.annotation.Nonnull Client client) throws ApiException { + ApiResponse localVarResp = testClassnameWithHttpInfo(client); + return localVarResp.getData(); + } + + /** + * To test class name in snake case + * To test class name in snake case + * @param client client model (required) + * @return ApiResponse<Client> + * @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 successful operation -
+ */ + public ApiResponse testClassnameWithHttpInfo(@javax.annotation.Nonnull Client client) throws ApiException { + okhttp3.Call localVarCall = testClassnameValidateBeforeCall(client, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * To test class name in snake case (asynchronously) + * To test class name in snake case + * @param client client model (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 successful operation -
+ */ + public okhttp3.Call testClassnameAsync(@javax.annotation.Nonnull Client client, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testClassnameValidateBeforeCall(client, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/PetApi.java new file mode 100644 index 000000000000..356fce3572e0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/PetApi.java @@ -0,0 +1,1325 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for addPet + * @param pet Pet object that needs to be added to the store (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
405 Invalid input -
+ */ + public okhttp3.Call addPetCall(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { "http://petstore.swagger.io/v2", "http://path-server-test.petstore.local/v2" }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/pet"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json", + "application/xml" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call addPetValidateBeforeCall(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'pet' is set + if (pet == null) { + throw new ApiException("Missing the required parameter 'pet' when calling addPet(Async)"); + } + + return addPetCall(pet, _callback); + + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store (required) + * @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
405 Invalid input -
+ */ + public void addPet(@javax.annotation.Nonnull Pet pet) throws ApiException { + addPetWithHttpInfo(pet); + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @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
405 Invalid input -
+ */ + public ApiResponse addPetWithHttpInfo(@javax.annotation.Nonnull Pet pet) throws ApiException { + okhttp3.Call localVarCall = addPetValidateBeforeCall(pet, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param pet Pet object that needs to be added to the store (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
405 Invalid input -
+ */ + public okhttp3.Call addPetAsync(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = addPetValidateBeforeCall(pet, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for deletePet + * @param petId Pet id to delete (required) + * @param apiKey (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
400 Invalid pet value -
+ */ + public okhttp3.Call deletePetCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey, 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 = "/pet/{petId}" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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); + } + + if (apiKey != null) { + localVarHeaderParams.put("api_key", localVarApiClient.parameterToString(apiKey)); + } + + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call deletePetValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + return deletePetCall(petId, apiKey, _callback); + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @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
400 Invalid pet value -
+ */ + public void deletePet(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @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
400 Invalid pet value -
+ */ + public ApiResponse deletePetWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey) throws ApiException { + okhttp3.Call localVarCall = deletePetValidateBeforeCall(petId, apiKey, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (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
400 Invalid pet value -
+ */ + public okhttp3.Call deletePetAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String apiKey, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = deletePetValidateBeforeCall(petId, apiKey, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for findPetsByStatus + * @param status Status values that need to be considered for filter (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 successful operation -
400 Invalid status value -
+ */ + public okhttp3.Call findPetsByStatusCall(@javax.annotation.Nonnull List status, 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 = "/pet/findByStatus"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (status != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "status", status)); + } + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call findPetsByStatusValidateBeforeCall(@javax.annotation.Nonnull List status, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + return findPetsByStatusCall(status, _callback); + + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return List<Pet> + * @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 successful operation -
400 Invalid status value -
+ */ + public List findPetsByStatus(@javax.annotation.Nonnull List status) throws ApiException { + ApiResponse> localVarResp = findPetsByStatusWithHttpInfo(status); + return localVarResp.getData(); + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @return ApiResponse<List<Pet>> + * @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 successful operation -
400 Invalid status value -
+ */ + public ApiResponse> findPetsByStatusWithHttpInfo(@javax.annotation.Nonnull List status) throws ApiException { + okhttp3.Call localVarCall = findPetsByStatusValidateBeforeCall(status, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (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 successful operation -
400 Invalid status value -
+ */ + public okhttp3.Call findPetsByStatusAsync(@javax.annotation.Nonnull List status, final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = findPetsByStatusValidateBeforeCall(status, _callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for findPetsByTags + * @param tags Tags to filter by (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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public okhttp3.Call findPetsByTagsCall(@javax.annotation.Nonnull List tags, 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 = "/pet/findByTags"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (tags != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "tags", tags)); + } + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @Deprecated + @SuppressWarnings("rawtypes") + private okhttp3.Call findPetsByTagsValidateBeforeCall(@javax.annotation.Nonnull List tags, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + return findPetsByTagsCall(tags, _callback); + + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return List<Pet> + * @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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public List findPetsByTags(@javax.annotation.Nonnull List tags) throws ApiException { + ApiResponse> localVarResp = findPetsByTagsWithHttpInfo(tags); + return localVarResp.getData(); + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @return ApiResponse<List<Pet>> + * @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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public ApiResponse> findPetsByTagsWithHttpInfo(@javax.annotation.Nonnull List tags) throws ApiException { + okhttp3.Call localVarCall = findPetsByTagsValidateBeforeCall(tags, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (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 successful operation -
400 Invalid tag value -
+ * @deprecated + */ + @Deprecated + public okhttp3.Call findPetsByTagsAsync(@javax.annotation.Nonnull List tags, final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = findPetsByTagsValidateBeforeCall(tags, _callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getPetById + * @param petId ID of pet to return (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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public okhttp3.Call getPetByIdCall(@javax.annotation.Nonnull Long petId, 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 = "/pet/{petId}" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { "api_key" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getPetByIdValidateBeforeCall(@javax.annotation.Nonnull Long petId, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + return getPetByIdCall(petId, _callback); + + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public Pet getPetById(@javax.annotation.Nonnull Long petId) throws ApiException { + ApiResponse localVarResp = getPetByIdWithHttpInfo(petId); + return localVarResp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public ApiResponse getPetByIdWithHttpInfo(@javax.annotation.Nonnull Long petId) throws ApiException { + okhttp3.Call localVarCall = getPetByIdValidateBeforeCall(petId, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (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 successful operation -
400 Invalid ID supplied -
404 Pet not found -
+ */ + public okhttp3.Call getPetByIdAsync(@javax.annotation.Nonnull Long petId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getPetByIdValidateBeforeCall(petId, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for updatePet + * @param pet Pet object that needs to be added to the store (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
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public okhttp3.Call updatePetCall(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { "http://petstore.swagger.io/v2", "http://path-server-test.petstore.local/v2" }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/pet"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json", + "application/xml" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updatePetValidateBeforeCall(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'pet' is set + if (pet == null) { + throw new ApiException("Missing the required parameter 'pet' when calling updatePet(Async)"); + } + + return updatePetCall(pet, _callback); + + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store (required) + * @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
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public void updatePet(@javax.annotation.Nonnull Pet pet) throws ApiException { + updatePetWithHttpInfo(pet); + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @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
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public ApiResponse updatePetWithHttpInfo(@javax.annotation.Nonnull Pet pet) throws ApiException { + okhttp3.Call localVarCall = updatePetValidateBeforeCall(pet, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Update an existing pet (asynchronously) + * + * @param pet Pet object that needs to be added to the store (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
400 Invalid ID supplied -
404 Pet not found -
405 Validation exception -
+ */ + public okhttp3.Call updatePetAsync(@javax.annotation.Nonnull Pet pet, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updatePetValidateBeforeCall(pet, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for updatePetWithForm + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (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
405 Invalid input -
+ */ + public okhttp3.Call updatePetWithFormCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status, 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 = "/pet/{petId}" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (name != null) { + localVarFormParams.put("name", name); + } + + if (status != null) { + localVarFormParams.put("status", status); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updatePetWithFormValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + return updatePetWithFormCall(petId, name, status, _callback); + + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @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
405 Invalid input -
+ */ + public void updatePetWithForm(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse<Void> + * @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
405 Invalid input -
+ */ + public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status) throws ApiException { + okhttp3.Call localVarCall = updatePetWithFormValidateBeforeCall(petId, name, status, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated (required) + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (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
405 Invalid input -
+ */ + public okhttp3.Call updatePetWithFormAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String name, @javax.annotation.Nullable String status, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updatePetWithFormValidateBeforeCall(petId, name, status, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for uploadFile + * @param petId ID of pet to update (required) + * @param contentType Content type header parameter (optional) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (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 successful operation -
+ */ + public okhttp3.Call uploadFileCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String contentType, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, 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 = "/pet/{petId}/uploadImage" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (additionalMetadata != null) { + localVarFormParams.put("additionalMetadata", additionalMetadata); + } + + if (_file != null) { + localVarFormParams.put("file", _file); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + if (contentType != null) { + localVarHeaderParams.put("Content-Type", localVarApiClient.parameterToString(contentType)); + } + + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call uploadFileValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String contentType, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + return uploadFileCall(petId, contentType, additionalMetadata, _file, _callback); + + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param contentType Content type header parameter (optional) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (optional) + * @return ModelApiResponse + * @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 successful operation -
+ */ + public ModelApiResponse uploadFile(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String contentType, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file) throws ApiException { + ApiResponse localVarResp = uploadFileWithHttpInfo(petId, contentType, additionalMetadata, _file); + return localVarResp.getData(); + } + + /** + * uploads an image + * + * @param petId ID of pet to update (required) + * @param contentType Content type header parameter (optional) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (optional) + * @return ApiResponse<ModelApiResponse> + * @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 successful operation -
+ */ + public ApiResponse uploadFileWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String contentType, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file) throws ApiException { + okhttp3.Call localVarCall = uploadFileValidateBeforeCall(petId, contentType, additionalMetadata, _file, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param contentType Content type header parameter (optional) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _file file to upload (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 successful operation -
+ */ + public okhttp3.Call uploadFileAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nullable String contentType, @javax.annotation.Nullable String additionalMetadata, @javax.annotation.Nullable File _file, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = uploadFileValidateBeforeCall(petId, contentType, additionalMetadata, _file, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for uploadFileWithRequiredFile + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (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 successful operation -
+ */ + public okhttp3.Call uploadFileWithRequiredFileCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nonnull File requiredFile, @javax.annotation.Nullable String additionalMetadata, 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 = "/fake/{petId}/uploadImageWithRequiredFile" + .replace("{" + "petId" + "}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (additionalMetadata != null) { + localVarFormParams.put("additionalMetadata", additionalMetadata); + } + + if (requiredFile != null) { + localVarFormParams.put("requiredFile", requiredFile); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call uploadFileWithRequiredFileValidateBeforeCall(@javax.annotation.Nonnull Long petId, @javax.annotation.Nonnull File requiredFile, @javax.annotation.Nullable String additionalMetadata, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFileWithRequiredFile(Async)"); + } + + // verify the required parameter 'requiredFile' is set + if (requiredFile == null) { + throw new ApiException("Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile(Async)"); + } + + return uploadFileWithRequiredFileCall(petId, requiredFile, additionalMetadata, _callback); + + } + + /** + * uploads an image (required) + * + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @return ModelApiResponse + * @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 successful operation -
+ */ + public ModelApiResponse uploadFileWithRequiredFile(@javax.annotation.Nonnull Long petId, @javax.annotation.Nonnull File requiredFile, @javax.annotation.Nullable String additionalMetadata) throws ApiException { + ApiResponse localVarResp = uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + return localVarResp.getData(); + } + + /** + * uploads an image (required) + * + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @return ApiResponse<ModelApiResponse> + * @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 successful operation -
+ */ + public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@javax.annotation.Nonnull Long petId, @javax.annotation.Nonnull File requiredFile, @javax.annotation.Nullable String additionalMetadata) throws ApiException { + okhttp3.Call localVarCall = uploadFileWithRequiredFileValidateBeforeCall(petId, requiredFile, additionalMetadata, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * uploads an image (required) (asynchronously) + * + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (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 successful operation -
+ */ + public okhttp3.Call uploadFileWithRequiredFileAsync(@javax.annotation.Nonnull Long petId, @javax.annotation.Nonnull File requiredFile, @javax.annotation.Nullable String additionalMetadata, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = uploadFileWithRequiredFileValidateBeforeCall(petId, requiredFile, additionalMetadata, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/StoreApi.java new file mode 100644 index 000000000000..d6399ce1d29b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/StoreApi.java @@ -0,0 +1,589 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import org.openapitools.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for deleteOrder + * @param orderId ID of the order that needs to be deleted (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
400 Invalid ID supplied -
404 Order not found -
+ */ + public okhttp3.Call deleteOrderCall(@javax.annotation.Nonnull String orderId, 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 = "/store/order/{order_id}" + .replace("{" + "order_id" + "}", localVarApiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call deleteOrderValidateBeforeCall(@javax.annotation.Nonnull String orderId, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + return deleteOrderCall(orderId, _callback); + + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @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
400 Invalid ID supplied -
404 Order not found -
+ */ + public void deleteOrder(@javax.annotation.Nonnull String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (required) + * @return ApiResponse<Void> + * @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
400 Invalid ID supplied -
404 Order not found -
+ */ + public ApiResponse deleteOrderWithHttpInfo(@javax.annotation.Nonnull String orderId) throws ApiException { + okhttp3.Call localVarCall = deleteOrderValidateBeforeCall(orderId, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Delete purchase order by ID (asynchronously) + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted (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
400 Invalid ID supplied -
404 Order not found -
+ */ + public okhttp3.Call deleteOrderAsync(@javax.annotation.Nonnull String orderId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = deleteOrderValidateBeforeCall(orderId, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for getInventory + * @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 successful operation -
+ */ + public okhttp3.Call getInventoryCall(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 = "/store/inventory"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { "api_key" }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getInventoryValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return getInventoryCall(_callback); + + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @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 successful operation -
+ */ + public Map getInventory() throws ApiException { + ApiResponse> localVarResp = getInventoryWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @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 successful operation -
+ */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getInventoryValidateBeforeCall(null); + Type localVarReturnType = new TypeToken>(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @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 successful operation -
+ */ + public okhttp3.Call getInventoryAsync(final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = getInventoryValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getOrderById + * @param orderId ID of pet that needs to be fetched (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 successful operation -
400 Invalid ID supplied -
404 Order not found -
+ */ + public okhttp3.Call getOrderByIdCall(@javax.annotation.Nonnull Long orderId, 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 = "/store/order/{order_id}" + .replace("{" + "order_id" + "}", localVarApiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getOrderByIdValidateBeforeCall(@javax.annotation.Nonnull Long orderId, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + return getOrderByIdCall(orderId, _callback); + + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return Order + * @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 successful operation -
400 Invalid ID supplied -
404 Order not found -
+ */ + public Order getOrderById(@javax.annotation.Nonnull Long orderId) throws ApiException { + ApiResponse localVarResp = getOrderByIdWithHttpInfo(orderId); + return localVarResp.getData(); + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * @param orderId ID of pet that needs to be fetched (required) + * @return ApiResponse<Order> + * @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 successful operation -
400 Invalid ID supplied -
404 Order not found -
+ */ + public ApiResponse getOrderByIdWithHttpInfo(@javax.annotation.Nonnull Long orderId) throws ApiException { + okhttp3.Call localVarCall = getOrderByIdValidateBeforeCall(orderId, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * @param orderId ID of pet that needs to be fetched (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 successful operation -
400 Invalid ID supplied -
404 Order not found -
+ */ + public okhttp3.Call getOrderByIdAsync(@javax.annotation.Nonnull Long orderId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getOrderByIdValidateBeforeCall(orderId, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for placeOrder + * @param order order placed for purchasing the pet (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 successful operation -
400 Invalid Order -
+ */ + public okhttp3.Call placeOrderCall(@javax.annotation.Nonnull Order order, 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 = order; + + // create path and map variables + String localVarPath = "/store/order"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call placeOrderValidateBeforeCall(@javax.annotation.Nonnull Order order, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'order' is set + if (order == null) { + throw new ApiException("Missing the required parameter 'order' when calling placeOrder(Async)"); + } + + return placeOrderCall(order, _callback); + + } + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet (required) + * @return Order + * @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 successful operation -
400 Invalid Order -
+ */ + public Order placeOrder(@javax.annotation.Nonnull Order order) throws ApiException { + ApiResponse localVarResp = placeOrderWithHttpInfo(order); + return localVarResp.getData(); + } + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @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 successful operation -
400 Invalid Order -
+ */ + public ApiResponse placeOrderWithHttpInfo(@javax.annotation.Nonnull Order order) throws ApiException { + okhttp3.Call localVarCall = placeOrderValidateBeforeCall(order, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param order order placed for purchasing the pet (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 successful operation -
400 Invalid Order -
+ */ + public okhttp3.Call placeOrderAsync(@javax.annotation.Nonnull Order order, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = placeOrderValidateBeforeCall(order, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/UserApi.java new file mode 100644 index 000000000000..94b8f35b3647 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/UserApi.java @@ -0,0 +1,1101 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import java.time.OffsetDateTime; +import org.openapitools.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for createUser + * @param user Created user object (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
0 successful operation -
+ */ + public okhttp3.Call createUserCall(@javax.annotation.Nonnull User user, 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 = user; + + // create path and map variables + String localVarPath = "/user"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call createUserValidateBeforeCall(@javax.annotation.Nonnull User user, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling createUser(Async)"); + } + + return createUserCall(user, _callback); + + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object (required) + * @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
0 successful operation -
+ */ + public void createUser(@javax.annotation.Nonnull User user) throws ApiException { + createUserWithHttpInfo(user); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object (required) + * @return ApiResponse<Void> + * @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
0 successful operation -
+ */ + public ApiResponse createUserWithHttpInfo(@javax.annotation.Nonnull User user) throws ApiException { + okhttp3.Call localVarCall = createUserValidateBeforeCall(user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param user Created user object (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
0 successful operation -
+ */ + public okhttp3.Call createUserAsync(@javax.annotation.Nonnull User user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = createUserValidateBeforeCall(user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for createUsersWithArrayInput + * @param user List of user object (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
0 successful operation -
+ */ + public okhttp3.Call createUsersWithArrayInputCall(@javax.annotation.Nonnull List user, 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 = user; + + // create path and map variables + String localVarPath = "/user/createWithArray"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call createUsersWithArrayInputValidateBeforeCall(@javax.annotation.Nonnull List user, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling createUsersWithArrayInput(Async)"); + } + + return createUsersWithArrayInputCall(user, _callback); + + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @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
0 successful operation -
+ */ + public void createUsersWithArrayInput(@javax.annotation.Nonnull List user) throws ApiException { + createUsersWithArrayInputWithHttpInfo(user); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return ApiResponse<Void> + * @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
0 successful operation -
+ */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(@javax.annotation.Nonnull List user) throws ApiException { + okhttp3.Call localVarCall = createUsersWithArrayInputValidateBeforeCall(user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param user List of user object (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
0 successful operation -
+ */ + public okhttp3.Call createUsersWithArrayInputAsync(@javax.annotation.Nonnull List user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = createUsersWithArrayInputValidateBeforeCall(user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for createUsersWithListInput + * @param user List of user object (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
0 successful operation -
+ */ + public okhttp3.Call createUsersWithListInputCall(@javax.annotation.Nonnull List user, 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 = user; + + // create path and map variables + String localVarPath = "/user/createWithList"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call createUsersWithListInputValidateBeforeCall(@javax.annotation.Nonnull List user, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling createUsersWithListInput(Async)"); + } + + return createUsersWithListInputCall(user, _callback); + + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @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
0 successful operation -
+ */ + public void createUsersWithListInput(@javax.annotation.Nonnull List user) throws ApiException { + createUsersWithListInputWithHttpInfo(user); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return ApiResponse<Void> + * @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
0 successful operation -
+ */ + public ApiResponse createUsersWithListInputWithHttpInfo(@javax.annotation.Nonnull List user) throws ApiException { + okhttp3.Call localVarCall = createUsersWithListInputValidateBeforeCall(user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param user List of user object (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
0 successful operation -
+ */ + public okhttp3.Call createUsersWithListInputAsync(@javax.annotation.Nonnull List user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = createUsersWithListInputValidateBeforeCall(user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for deleteUser + * @param username The name that needs to be deleted (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
400 Invalid username supplied -
404 User not found -
+ */ + public okhttp3.Call deleteUserCall(@javax.annotation.Nonnull String username, 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 = "/user/{username}" + .replace("{" + "username" + "}", localVarApiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call deleteUserValidateBeforeCall(@javax.annotation.Nonnull String username, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + return deleteUserCall(username, _callback); + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @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
400 Invalid username supplied -
404 User not found -
+ */ + public void deleteUser(@javax.annotation.Nonnull String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @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
400 Invalid username supplied -
404 User not found -
+ */ + public ApiResponse deleteUserWithHttpInfo(@javax.annotation.Nonnull String username) throws ApiException { + okhttp3.Call localVarCall = deleteUserValidateBeforeCall(username, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (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
400 Invalid username supplied -
404 User not found -
+ */ + public okhttp3.Call deleteUserAsync(@javax.annotation.Nonnull String username, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = deleteUserValidateBeforeCall(username, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for getUserByName + * @param username The name that needs to be fetched. Use user1 for testing. (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 successful operation -
400 Invalid username supplied -
404 User not found -
+ */ + public okhttp3.Call getUserByNameCall(@javax.annotation.Nonnull String username, 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 = "/user/{username}" + .replace("{" + "username" + "}", localVarApiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getUserByNameValidateBeforeCall(@javax.annotation.Nonnull String username, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + return getUserByNameCall(username, _callback); + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @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 successful operation -
400 Invalid username supplied -
404 User not found -
+ */ + public User getUserByName(@javax.annotation.Nonnull String username) throws ApiException { + ApiResponse localVarResp = getUserByNameWithHttpInfo(username); + return localVarResp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @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 successful operation -
400 Invalid username supplied -
404 User not found -
+ */ + public ApiResponse getUserByNameWithHttpInfo(@javax.annotation.Nonnull String username) throws ApiException { + okhttp3.Call localVarCall = getUserByNameValidateBeforeCall(username, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (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 successful operation -
400 Invalid username supplied -
404 User not found -
+ */ + public okhttp3.Call getUserByNameAsync(@javax.annotation.Nonnull String username, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getUserByNameValidateBeforeCall(username, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for loginUser + * @param username The user name for login (required) + * @param password The password for login in clear text (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 successful operation * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
400 Invalid username/password supplied -
+ */ + public okhttp3.Call loginUserCall(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull String password, 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 = "/user/login"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (username != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("username", username)); + } + + if (password != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("password", password)); + } + + final String[] localVarAccepts = { + "application/xml", + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call loginUserValidateBeforeCall(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull String password, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + return loginUserCall(username, password, _callback); + + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (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 successful operation * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
400 Invalid username/password supplied -
+ */ + public String loginUser(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull String password) throws ApiException { + ApiResponse localVarResp = loginUserWithHttpInfo(username, password); + return localVarResp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (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 successful operation * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
400 Invalid username/password supplied -
+ */ + public ApiResponse loginUserWithHttpInfo(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull String password) throws ApiException { + okhttp3.Call localVarCall = loginUserValidateBeforeCall(username, password, null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (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 successful operation * X-Rate-Limit - calls per hour allowed by the user
* X-Expires-After - date in UTC when token expires
400 Invalid username/password supplied -
+ */ + public okhttp3.Call loginUserAsync(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull String password, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = loginUserValidateBeforeCall(username, password, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for logoutUser + * @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
0 successful operation -
+ */ + public okhttp3.Call logoutUserCall(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 = "/user/logout"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + 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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call logoutUserValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return logoutUserCall(_callback); + + } + + /** + * Logs out current logged in user session + * + * @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
0 successful operation -
+ */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @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
0 successful operation -
+ */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = logoutUserValidateBeforeCall(null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @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
0 successful operation -
+ */ + public okhttp3.Call logoutUserAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = logoutUserValidateBeforeCall(_callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for updateUser + * @param username name that need to be deleted (required) + * @param user Updated user object (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
400 Invalid user supplied -
404 User not found -
+ */ + public okhttp3.Call updateUserCall(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull User user, 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 = user; + + // create path and map variables + String localVarPath = "/user/{username}" + .replace("{" + "username" + "}", localVarApiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updateUserValidateBeforeCall(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull User user, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling updateUser(Async)"); + } + + return updateUserCall(username, user, _callback); + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @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
400 Invalid user supplied -
404 User not found -
+ */ + public void updateUser(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull User user) throws ApiException { + updateUserWithHttpInfo(username, user); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @return ApiResponse<Void> + * @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
400 Invalid user supplied -
404 User not found -
+ */ + public ApiResponse updateUserWithHttpInfo(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull User user) throws ApiException { + okhttp3.Call localVarCall = updateUserValidateBeforeCall(username, user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (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
400 Invalid user supplied -
404 User not found -
+ */ + public okhttp3.Call updateUserAsync(@javax.annotation.Nonnull String username, @javax.annotation.Nonnull User user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updateUserValidateBeforeCall(username, user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/ValuesApi.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/ValuesApi.java new file mode 100644 index 000000000000..0722e9e47546 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/api/ValuesApi.java @@ -0,0 +1,195 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import com.google.gson.reflect.TypeToken; + + + +import org.openapitools.client.model.Variable; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ValuesApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public ValuesApi() { + this(Configuration.getDefaultApiClient()); + } + + public ValuesApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for getSomeValues + * @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 successful operation -
400 Invalid Value -
+ */ + public okhttp3.Call getSomeValuesCall(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 = "/values"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/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[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getSomeValuesValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return getSomeValuesCall(_callback); + + } + + /** + * Get some primitive variable values + * + * @return Variable + * @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 successful operation -
400 Invalid Value -
+ */ + public Variable getSomeValues() throws ApiException { + ApiResponse localVarResp = getSomeValuesWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Get some primitive variable values + * + * @return ApiResponse<Variable> + * @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 successful operation -
400 Invalid Value -
+ */ + public ApiResponse getSomeValuesWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getSomeValuesValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + + + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get some primitive variable values (asynchronously) + * + * @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 successful operation -
400 Invalid Value -
+ */ + public okhttp3.Call getSomeValuesAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getSomeValuesValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..040536a6300f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 000000000000..859fff94b6a0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @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 ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, byte[] payload, String method, URI uri) throws ApiException; +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..e3be356c7dfe --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + // UTF-8 explicitly: Credentials.basic defaults to ISO-8859-1, which turns every character + // outside Latin-1 into '?'. This matches the shared Java HttpBasicAuth template. It differs on + // purpose from okhttp-gson and retrofit2, which keep the ISO-8859-1 default, so for such + // credentials this library sends a different Authorization header than okhttp-gson does. + headerParams.put("Authorization", Credentials.basic(username == null ? "" : username, password == null ? "" : password, StandardCharsets.UTF_8)); + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 000000000000..1abfe5400723 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; +import java.util.Optional; +import java.util.function.Supplier; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier == null ? null : tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token + */ + public void setBearerToken(String 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 + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/OAuth.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/OAuth.java new file mode 100644 index 000000000000..d3b2bf1d573a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/OAuth.java @@ -0,0 +1,43 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + if (accessToken == null) { + return; + } + headerParams.put("Authorization", "Bearer " + accessToken); + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/OAuthFlow.java new file mode 100644 index 000000000000..9fafb844f9d9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/OAuthFlow.java @@ -0,0 +1,25 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +/** + * OAuth flows that are supported by this client + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public enum OAuthFlow { + ACCESS_CODE, //called authorizationCode in OpenAPI 3.0 + IMPLICIT, + PASSWORD, + APPLICATION //called clientCredentials in OpenAPI 3.0 +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/RetryingOAuth.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/RetryingOAuth.java new file mode 100644 index 000000000000..0b8b2b49819e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/auth/RetryingOAuth.java @@ -0,0 +1,245 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.JSON; +import org.openapitools.client.Pair; + +import okhttp3.FormBody; +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RetryingOAuth extends OAuth implements Interceptor { + private final OkHttpClient client; + private final TokenRequestBuilder tokenRequestBuilder; + private final JSON json; + + public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) { + this.client = client; + this.tokenRequestBuilder = tokenRequestBuilder; + this.json = new JSON(); + } + + public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) { + this(new OkHttpClient(), tokenRequestBuilder); + } + + public RetryingOAuth( + String tokenUrl, + String clientId, + OAuthFlow flow, + String clientSecret, + Map parameters + ) { + this(TokenRequestBuilder.tokenLocation(tokenUrl) + .setClientId(clientId) + .setClientSecret(clientSecret)); + setFlow(flow); + if (parameters != null) { + for (Map.Entry entry : parameters.entrySet()) { + tokenRequestBuilder.setParameter(entry.getKey(), entry.getValue()); + } + } + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case ACCESS_CODE: + tokenRequestBuilder.setGrantType("authorization_code"); + break; + case IMPLICIT: + tokenRequestBuilder.setGrantType("implicit"); + break; + case PASSWORD: + tokenRequestBuilder.setGrantType("password"); + break; + case APPLICATION: + tokenRequestBuilder.setGrantType("client_credentials"); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) throws IOException { + return retryingIntercept(chain, true); + } + + private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException { + Request request = chain.request(); + + // If the request already has an authorization (e.g. Basic auth), proceed with the request as is + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // Get the token if it has not yet been acquired + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Remember the token this request is sent with: a 401/403 must only trigger a token refresh + // if no other thread has refreshed the token in the meantime (see updateAccessToken). + String requestAccessToken = getAccessToken(); + if (requestAccessToken != null) { + // Build the request + Request.Builder requestBuilder = request.newBuilder(); + requestBuilder.header("Authorization", "Bearer " + requestAccessToken); + + // Execute the request + Response response = chain.proceed(requestBuilder.build()); + + // 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row + if ( + response != null && + ( response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || + response.code() == HttpURLConnection.HTTP_FORBIDDEN ) && + updateTokenAndRetryOnAuthorizationFailure + ) { + try { + if (updateAccessToken(requestAccessToken)) { + if (response.body() != null) { + response.body().close(); + } + return retryingIntercept(chain, false); + } + } catch (Exception e) { + if (response.body() != null) { + response.body().close(); + } + throw e; + } + } + return response; + } + else { + return chain.proceed(chain.request()); + } + } + + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + Request tokenRequest = tokenRequestBuilder.build(); + try (Response response = client.newCall(tokenRequest).execute()) { + String body = response.body().string(); + if (!response.isSuccessful()) { + // surface the token endpoint's answer instead of silently sending the request unauthenticated + throw new IOException("OAuth token request to " + tokenRequest.url() + " failed with HTTP " + + response.code() + (body.isEmpty() ? "" : ": " + body)); + } + AccessTokenResponse tokenResponse; + try { + tokenResponse = json.deserialize(body, AccessTokenResponse.class); + } catch (RuntimeException e) { + throw new IOException("OAuth token response from " + tokenRequest.url() + " could not be parsed: " + body, e); + } + if (tokenResponse == null || tokenResponse.accessToken == null) { + throw new IOException("OAuth token response from " + tokenRequest.url() + " contains no access_token: " + body); + } + setAccessToken(tokenResponse.accessToken); + } + } + return getAccessToken() == null || !getAccessToken().equals(requestAccessToken); + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + byte[] payload, String method, URI uri) throws ApiException { + // No implementation necessary + } + + public static class AccessTokenResponse { + @com.google.gson.annotations.SerializedName("access_token") + public String accessToken; + + @com.google.gson.annotations.SerializedName("token_type") + public String tokenType; + + @com.google.gson.annotations.SerializedName("expires_in") + public Long expiresIn; + + @com.google.gson.annotations.SerializedName("refresh_token") + public String refreshToken; + + @com.google.gson.annotations.SerializedName("scope") + public String scope; + } + + public static class TokenRequestBuilder { + private String tokenUrl; + private String clientId; + private String clientSecret; + private String grantType; + private final Map parameters = new HashMap<>(); + + public static TokenRequestBuilder tokenLocation(String tokenUrl) { + return new TokenRequestBuilder().setTokenUrl(tokenUrl); + } + + public TokenRequestBuilder setTokenUrl(String tokenUrl) { + this.tokenUrl = tokenUrl; + return this; + } + + public TokenRequestBuilder setClientId(String clientId) { + this.clientId = clientId; + return this; + } + + public TokenRequestBuilder setClientSecret(String clientSecret) { + this.clientSecret = clientSecret; + return this; + } + + public TokenRequestBuilder setGrantType(String grantType) { + this.grantType = grantType; + return this; + } + + public TokenRequestBuilder setParameter(String name, String value) { + this.parameters.put(name, value); + return this; + } + + public Request build() { + FormBody.Builder formBuilder = new FormBody.Builder(); + if (grantType != null) formBuilder.add("grant_type", grantType); + if (clientId != null) formBuilder.add("client_id", clientId); + if (clientSecret != null) formBuilder.add("client_secret", clientSecret); + for (Map.Entry entry : parameters.entrySet()) { + formBuilder.add(entry.getKey(), entry.getValue()); + } + + return new Request.Builder() + .url(tokenUrl) + .post(formBuilder.build()) + .build(); + } + } +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 000000000000..caf9bf751735 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,139 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Map; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map> getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).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) { + return o == null ? "null" : o.toString().replace("\n", "\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + +} diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java new file mode 100644 index 000000000000..47a78e12e046 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,494 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * AdditionalPropertiesClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AdditionalPropertiesClass { + public static final String SERIALIZED_NAME_MAP_PROPERTY = "map_property"; + @SerializedName(SERIALIZED_NAME_MAP_PROPERTY) + @javax.annotation.Nullable + private Map mapProperty = new HashMap<>(); + + public static final String SERIALIZED_NAME_MAP_OF_MAP_PROPERTY = "map_of_map_property"; + @SerializedName(SERIALIZED_NAME_MAP_OF_MAP_PROPERTY) + @javax.annotation.Nullable + private Map> mapOfMapProperty = new HashMap<>(); + + public static final String SERIALIZED_NAME_ANYTYPE1 = "anytype_1"; + @SerializedName(SERIALIZED_NAME_ANYTYPE1) + @javax.annotation.Nullable + private Object anytype1 = null; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1 = "map_with_undeclared_properties_anytype_1"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1) + @javax.annotation.Nullable + private Object mapWithUndeclaredPropertiesAnytype1; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2 = "map_with_undeclared_properties_anytype_2"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2) + @javax.annotation.Nullable + private Object mapWithUndeclaredPropertiesAnytype2; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3 = "map_with_undeclared_properties_anytype_3"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3) + @javax.annotation.Nullable + private Map mapWithUndeclaredPropertiesAnytype3 = new HashMap<>(); + + public static final String SERIALIZED_NAME_EMPTY_MAP = "empty_map"; + @SerializedName(SERIALIZED_NAME_EMPTY_MAP) + @javax.annotation.Nullable + private Object emptyMap; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_STRING = "map_with_undeclared_properties_string"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_STRING) + @javax.annotation.Nullable + private Map mapWithUndeclaredPropertiesString = new HashMap<>(); + + public AdditionalPropertiesClass() { + } + + public AdditionalPropertiesClass mapProperty(@javax.annotation.Nullable Map mapProperty) { + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + if (this.mapProperty == null) { + this.mapProperty = new HashMap<>(); + } + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + */ + @javax.annotation.Nullable + + public Map getMapProperty() { + return mapProperty; + } + + public void setMapProperty(@javax.annotation.Nullable Map mapProperty) { + this.mapProperty = mapProperty; + } + + + public AdditionalPropertiesClass mapOfMapProperty(@javax.annotation.Nullable Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + if (this.mapOfMapProperty == null) { + this.mapOfMapProperty = new HashMap<>(); + } + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + */ + @javax.annotation.Nullable + + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + public void setMapOfMapProperty(@javax.annotation.Nullable Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + public AdditionalPropertiesClass anytype1(@javax.annotation.Nullable Object anytype1) { + this.anytype1 = anytype1; + return this; + } + + /** + * Get anytype1 + * @return anytype1 + */ + @javax.annotation.Nullable + + public Object getAnytype1() { + return anytype1; + } + + public void setAnytype1(@javax.annotation.Nullable Object anytype1) { + this.anytype1 = anytype1; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype1(@javax.annotation.Nullable Object mapWithUndeclaredPropertiesAnytype1) { + this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; + return this; + } + + /** + * Get mapWithUndeclaredPropertiesAnytype1 + * @return mapWithUndeclaredPropertiesAnytype1 + */ + @javax.annotation.Nullable + + public Object getMapWithUndeclaredPropertiesAnytype1() { + return mapWithUndeclaredPropertiesAnytype1; + } + + public void setMapWithUndeclaredPropertiesAnytype1(@javax.annotation.Nullable Object mapWithUndeclaredPropertiesAnytype1) { + this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype2(@javax.annotation.Nullable Object mapWithUndeclaredPropertiesAnytype2) { + this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; + return this; + } + + /** + * Get mapWithUndeclaredPropertiesAnytype2 + * @return mapWithUndeclaredPropertiesAnytype2 + */ + @javax.annotation.Nullable + + public Object getMapWithUndeclaredPropertiesAnytype2() { + return mapWithUndeclaredPropertiesAnytype2; + } + + public void setMapWithUndeclaredPropertiesAnytype2(@javax.annotation.Nullable Object mapWithUndeclaredPropertiesAnytype2) { + this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype3(@javax.annotation.Nullable Map mapWithUndeclaredPropertiesAnytype3) { + this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; + return this; + } + + public AdditionalPropertiesClass putMapWithUndeclaredPropertiesAnytype3Item(String key, Object mapWithUndeclaredPropertiesAnytype3Item) { + if (this.mapWithUndeclaredPropertiesAnytype3 == null) { + this.mapWithUndeclaredPropertiesAnytype3 = new HashMap<>(); + } + this.mapWithUndeclaredPropertiesAnytype3.put(key, mapWithUndeclaredPropertiesAnytype3Item); + return this; + } + + /** + * Get mapWithUndeclaredPropertiesAnytype3 + * @return mapWithUndeclaredPropertiesAnytype3 + */ + @javax.annotation.Nullable + + public Map getMapWithUndeclaredPropertiesAnytype3() { + return mapWithUndeclaredPropertiesAnytype3; + } + + public void setMapWithUndeclaredPropertiesAnytype3(@javax.annotation.Nullable Map mapWithUndeclaredPropertiesAnytype3) { + this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; + } + + + public AdditionalPropertiesClass emptyMap(@javax.annotation.Nullable Object emptyMap) { + this.emptyMap = emptyMap; + return this; + } + + /** + * an object with no declared properties and no undeclared properties, hence it's an empty map. + * @return emptyMap + */ + @javax.annotation.Nullable + + public Object getEmptyMap() { + return emptyMap; + } + + public void setEmptyMap(@javax.annotation.Nullable Object emptyMap) { + this.emptyMap = emptyMap; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesString(@javax.annotation.Nullable Map mapWithUndeclaredPropertiesString) { + this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + return this; + } + + public AdditionalPropertiesClass putMapWithUndeclaredPropertiesStringItem(String key, String mapWithUndeclaredPropertiesStringItem) { + if (this.mapWithUndeclaredPropertiesString == null) { + this.mapWithUndeclaredPropertiesString = new HashMap<>(); + } + this.mapWithUndeclaredPropertiesString.put(key, mapWithUndeclaredPropertiesStringItem); + return this; + } + + /** + * Get mapWithUndeclaredPropertiesString + * @return mapWithUndeclaredPropertiesString + */ + @javax.annotation.Nullable + + public Map getMapWithUndeclaredPropertiesString() { + return mapWithUndeclaredPropertiesString; + } + + public void setMapWithUndeclaredPropertiesString(@javax.annotation.Nullable Map mapWithUndeclaredPropertiesString) { + this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AdditionalPropertiesClass instance itself + */ + public AdditionalPropertiesClass putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty) && + Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && + Objects.equals(this.mapWithUndeclaredPropertiesAnytype1, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype1) && + Objects.equals(this.mapWithUndeclaredPropertiesAnytype2, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype2) && + Objects.equals(this.mapWithUndeclaredPropertiesAnytype3, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype3) && + Objects.equals(this.emptyMap, additionalPropertiesClass.emptyMap) && + Objects.equals(this.mapWithUndeclaredPropertiesString, additionalPropertiesClass.mapWithUndeclaredPropertiesString)&& + Objects.equals(this.additionalProperties, additionalPropertiesClass.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty, anytype1, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, emptyMap, mapWithUndeclaredPropertiesString, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append(" anytype1: ").append(toIndentedString(anytype1)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesAnytype1: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype1)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesAnytype2: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype2)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesAnytype3: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype3)).append("\n"); + sb.append(" emptyMap: ").append(toIndentedString(emptyMap)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesString: ").append(toIndentedString(mapWithUndeclaredPropertiesString)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("map_property", "map_of_map_property", "anytype_1", "map_with_undeclared_properties_anytype_1", "map_with_undeclared_properties_anytype_2", "map_with_undeclared_properties_anytype_3", "empty_map", "map_with_undeclared_properties_string")); + + // 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 AdditionalPropertiesClass + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AdditionalPropertiesClass is not found in the empty JSON string", AdditionalPropertiesClass.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AdditionalPropertiesClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AdditionalPropertiesClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AdditionalPropertiesClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AdditionalPropertiesClass read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AdditionalPropertiesClass instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AdditionalPropertiesClass given an JSON string + * + * @param jsonString JSON string + * @return An instance of AdditionalPropertiesClass + * @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesClass + */ + public static AdditionalPropertiesClass fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AdditionalPropertiesClass.class); + } + + /** + * Convert an instance of AdditionalPropertiesClass to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java new file mode 100644 index 000000000000..6042a497296b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java @@ -0,0 +1,372 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * AllOfModelArrayAnyOf + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfModelArrayAnyOf { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name = "default-name"; + + public static final String SERIALIZED_NAME_LINK_LIST_COLUMN1 = "linkListColumn1"; + @SerializedName(SERIALIZED_NAME_LINK_LIST_COLUMN1) + @javax.annotation.Nullable + private AllOfModelArrayAnyOfAllOfLinkListColumn1 linkListColumn1; + + public static final String SERIALIZED_NAME_ATTRIBUTES = "attributes"; + @SerializedName(SERIALIZED_NAME_ATTRIBUTES) + @javax.annotation.Nullable + private AllOfModelArrayAnyOfAllOfAttributes attributes; + + public AllOfModelArrayAnyOf() { + } + + public AllOfModelArrayAnyOf id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public AllOfModelArrayAnyOf name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public AllOfModelArrayAnyOf linkListColumn1(@javax.annotation.Nullable AllOfModelArrayAnyOfAllOfLinkListColumn1 linkListColumn1) { + this.linkListColumn1 = linkListColumn1; + return this; + } + + /** + * Get linkListColumn1 + * @return linkListColumn1 + */ + @javax.annotation.Nullable + + public AllOfModelArrayAnyOfAllOfLinkListColumn1 getLinkListColumn1() { + return linkListColumn1; + } + + public void setLinkListColumn1(@javax.annotation.Nullable AllOfModelArrayAnyOfAllOfLinkListColumn1 linkListColumn1) { + this.linkListColumn1 = linkListColumn1; + } + + + public AllOfModelArrayAnyOf attributes(@javax.annotation.Nullable AllOfModelArrayAnyOfAllOfAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get attributes + * @return attributes + */ + @javax.annotation.Nullable + + public AllOfModelArrayAnyOfAllOfAttributes getAttributes() { + return attributes; + } + + public void setAttributes(@javax.annotation.Nullable AllOfModelArrayAnyOfAllOfAttributes attributes) { + this.attributes = attributes; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOf instance itself + */ + public AllOfModelArrayAnyOf putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfModelArrayAnyOf allOfModelArrayAnyOf = (AllOfModelArrayAnyOf) o; + return Objects.equals(this.id, allOfModelArrayAnyOf.id) && + Objects.equals(this.name, allOfModelArrayAnyOf.name) && + Objects.equals(this.linkListColumn1, allOfModelArrayAnyOf.linkListColumn1) && + Objects.equals(this.attributes, allOfModelArrayAnyOf.attributes)&& + Objects.equals(this.additionalProperties, allOfModelArrayAnyOf.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, linkListColumn1, attributes, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfModelArrayAnyOf {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" linkListColumn1: ").append(toIndentedString(linkListColumn1)).append("\n"); + sb.append(" attributes: ").append(toIndentedString(attributes)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name", "linkListColumn1", "attributes")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name")); + } + + /** + * 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 AllOfModelArrayAnyOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfModelArrayAnyOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AllOfModelArrayAnyOf is not found in the empty JSON string", AllOfModelArrayAnyOf.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AllOfModelArrayAnyOf.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // validate the optional field `linkListColumn1` + if (jsonObj.get("linkListColumn1") != null && !jsonObj.get("linkListColumn1").isJsonNull()) { + AllOfModelArrayAnyOfAllOfLinkListColumn1.validateJsonElement(jsonObj.get("linkListColumn1")); + } + // validate the optional field `attributes` + if (jsonObj.get("attributes") != null && !jsonObj.get("attributes").isJsonNull()) { + AllOfModelArrayAnyOfAllOfAttributes.validateJsonElement(jsonObj.get("attributes")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfModelArrayAnyOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfModelArrayAnyOf read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfModelArrayAnyOf instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfModelArrayAnyOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOf + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOf + */ + public static AllOfModelArrayAnyOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOf.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java new file mode 100644 index 000000000000..cb6af7143eec --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java @@ -0,0 +1,277 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * AllOfModelArrayAnyOfAllOfAttributes + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfModelArrayAnyOfAllOfAttributes { + public static final String SERIALIZED_NAME_C = "C"; + @SerializedName(SERIALIZED_NAME_C) + @javax.annotation.Nullable + private AllOfModelArrayAnyOfAllOfAttributesC C; + + public AllOfModelArrayAnyOfAllOfAttributes() { + } + + public AllOfModelArrayAnyOfAllOfAttributes C(@javax.annotation.Nullable AllOfModelArrayAnyOfAllOfAttributesC C) { + this.C = C; + return this; + } + + /** + * Get C + * @return C + */ + @javax.annotation.Nullable + + public AllOfModelArrayAnyOfAllOfAttributesC getC() { + return C; + } + + public void setC(@javax.annotation.Nullable AllOfModelArrayAnyOfAllOfAttributesC C) { + this.C = C; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOfAllOfAttributes instance itself + */ + public AllOfModelArrayAnyOfAllOfAttributes putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfModelArrayAnyOfAllOfAttributes allOfModelArrayAnyOfAllOfAttributes = (AllOfModelArrayAnyOfAllOfAttributes) o; + return Objects.equals(this.C, allOfModelArrayAnyOfAllOfAttributes.C)&& + Objects.equals(this.additionalProperties, allOfModelArrayAnyOfAllOfAttributes.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(C, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfModelArrayAnyOfAllOfAttributes {\n"); + sb.append(" C: ").append(toIndentedString(C)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("C")); + + // 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 AllOfModelArrayAnyOfAllOfAttributes + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfModelArrayAnyOfAllOfAttributes.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AllOfModelArrayAnyOfAllOfAttributes is not found in the empty JSON string", AllOfModelArrayAnyOfAllOfAttributes.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `C` + if (jsonObj.get("C") != null && !jsonObj.get("C").isJsonNull()) { + AllOfModelArrayAnyOfAllOfAttributesC.validateJsonElement(jsonObj.get("C")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfAttributes.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfAttributes' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfModelArrayAnyOfAllOfAttributes.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfAttributes value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfModelArrayAnyOfAllOfAttributes read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfModelArrayAnyOfAllOfAttributes instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfAttributes given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfAttributes + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfAttributes + */ + public static AllOfModelArrayAnyOfAllOfAttributes fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfAttributes.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfAttributes to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java new file mode 100644 index 000000000000..2dacf4b18505 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java @@ -0,0 +1,376 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfModelArrayAnyOfAllOfAttributesC extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AllOfModelArrayAnyOfAllOfAttributesC.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOfAllOfAttributesC instance itself + */ + public AllOfModelArrayAnyOfAllOfAttributesC putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(AllOfModelArrayAnyOfAllOfAttributesC instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(AllOfModelArrayAnyOfAllOfAttributesC value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 AllOfModelArrayAnyOfAllOfAttributesC + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize Pet + try { + // validate the JSON object to see if any exception is thrown + Pet.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Pet failed with `%s`.", e.getMessage())); + } + + // deserialize Order + try { + // validate the JSON object to see if any exception is thrown + Order.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Order failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for AllOfModelArrayAnyOfAllOfAttributesC: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfAttributesC.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfAttributesC' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterPet = gson.getDelegateAdapter(this, TypeToken.get(Pet.class)); + final TypeAdapter adapterOrder = gson.getDelegateAdapter(this, TypeToken.get(Order.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfAttributesC value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Pet` + if (value.getActualInstance() instanceof Pet) { + element = adapterPet.toJsonTree((Pet)value.getActualInstance()); + } + // check if the actual instance is of the type `Order` + if (value.getActualInstance() instanceof Order) { + element = adapterOrder.toJsonTree((Order)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Order, Pet"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public AllOfModelArrayAnyOfAllOfAttributesC read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Pet + try { + // validate the JSON object to see if any exception is thrown + Pet.validateJsonElement(jsonElement); + actualAdapter = adapterPet; + match++; + log.log(Level.FINER, "Input data matches schema 'Pet'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Pet failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Pet'", e); + } + + // deserialize Order + try { + // validate the JSON object to see if any exception is thrown + Order.validateJsonElement(jsonElement); + actualAdapter = adapterOrder; + match++; + log.log(Level.FINER, "Input data matches schema 'Order'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Order failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Order'", e); + } + + if (match == 1) { + AllOfModelArrayAnyOfAllOfAttributesC ret = new AllOfModelArrayAnyOfAllOfAttributesC(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for AllOfModelArrayAnyOfAllOfAttributesC: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public AllOfModelArrayAnyOfAllOfAttributesC() { + super("oneOf", Boolean.FALSE); + } + + public AllOfModelArrayAnyOfAllOfAttributesC(Pet o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public AllOfModelArrayAnyOfAllOfAttributesC(Order o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Pet", Pet.class); + schemas.put("Order", Order.class); + } + + @Override + public Map> getSchemas() { + return AllOfModelArrayAnyOfAllOfAttributesC.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Order, Pet + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Pet.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Order.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Order, Pet"); + } + + /** + * Get the actual instance, which can be the following: + * Order, Pet + * + * @return The actual instance (Order, Pet) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Pet`. If the actual instance is not `Pet`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Pet` + * @throws ClassCastException if the instance is not `Pet` + */ + @SuppressWarnings("unchecked") + public Pet getPet() throws ClassCastException { + return (Pet)super.getActualInstance(); + } + + /** + * Get the actual instance of `Order`. If the actual instance is not `Order`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Order` + * @throws ClassCastException if the instance is not `Order` + */ + @SuppressWarnings("unchecked") + public Order getOrder() throws ClassCastException { + return (Order)super.getActualInstance(); + } + + + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfAttributesC given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfAttributesC + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfAttributesC + */ + public static AllOfModelArrayAnyOfAllOfAttributesC fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfAttributesC.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfAttributesC to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java new file mode 100644 index 000000000000..74c315ed5435 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java @@ -0,0 +1,299 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfModelArrayAnyOfAllOfLinkListColumn1 { + public static final String SERIALIZED_NAME_VALUE = "value"; + @SerializedName(SERIALIZED_NAME_VALUE) + @javax.annotation.Nonnull + private List value = new ArrayList<>(); + + public AllOfModelArrayAnyOfAllOfLinkListColumn1() { + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1 value(@javax.annotation.Nonnull List value) { + this.value = value; + return this; + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1 addValueItem(AllOfModelArrayAnyOfAllOfLinkListColumn1Value valueItem) { + if (this.value == null) { + this.value = new ArrayList<>(); + } + this.value.add(valueItem); + return this; + } + + /** + * Get value + * @return value + */ + @javax.annotation.Nonnull + + public List getValue() { + return value; + } + + public void setValue(@javax.annotation.Nonnull List value) { + this.value = value; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOfAllOfLinkListColumn1 instance itself + */ + public AllOfModelArrayAnyOfAllOfLinkListColumn1 putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfModelArrayAnyOfAllOfLinkListColumn1 allOfModelArrayAnyOfAllOfLinkListColumn1 = (AllOfModelArrayAnyOfAllOfLinkListColumn1) o; + return Objects.equals(this.value, allOfModelArrayAnyOfAllOfLinkListColumn1.value)&& + Objects.equals(this.additionalProperties, allOfModelArrayAnyOfAllOfLinkListColumn1.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(value, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfModelArrayAnyOfAllOfLinkListColumn1 {\n"); + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("value")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("value")); + } + + /** + * 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 AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfModelArrayAnyOfAllOfLinkListColumn1.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AllOfModelArrayAnyOfAllOfLinkListColumn1 is not found in the empty JSON string", AllOfModelArrayAnyOfAllOfLinkListColumn1.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AllOfModelArrayAnyOfAllOfLinkListColumn1.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (jsonObj.get("value") != null) { + if (!jsonObj.get("value").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `value` to be an array in the JSON string but got `%s`", jsonObj.get("value").toString())); + } + com.google.gson.JsonArray jsonArrayvalue = jsonObj.getAsJsonArray("value"); + // validate the required field `value` (array) + for (int i = 0; i < jsonArrayvalue.size(); i++) { + AllOfModelArrayAnyOfAllOfLinkListColumn1Value.validateJsonElement(jsonArrayvalue.get(i)); + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfLinkListColumn1.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfLinkListColumn1' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfModelArrayAnyOfAllOfLinkListColumn1.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfLinkListColumn1 value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfModelArrayAnyOfAllOfLinkListColumn1 read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfModelArrayAnyOfAllOfLinkListColumn1 instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1 given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfLinkListColumn1 + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ + public static AllOfModelArrayAnyOfAllOfLinkListColumn1 fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfLinkListColumn1.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1 to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java new file mode 100644 index 000000000000..0a2681d4faf2 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java @@ -0,0 +1,368 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfModelArrayAnyOfAllOfLinkListColumn1Value extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AllOfModelArrayAnyOfAllOfLinkListColumn1Value.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOfAllOfLinkListColumn1Value instance itself + */ + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(AllOfModelArrayAnyOfAllOfLinkListColumn1Value instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched anyOf schema. + */ + private static void writeUnconsumedProperties(AllOfModelArrayAnyOfAllOfLinkListColumn1Value value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + try { + // validate the JSON object to see if any exception is thrown + User.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for User failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + Tag.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Tag failed with `%s`.", e.getMessage())); + } + + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for AllOfModelArrayAnyOfAllOfLinkListColumn1Value: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfLinkListColumn1Value.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfLinkListColumn1Value' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterUser = gson.getDelegateAdapter(this, TypeToken.get(User.class)); + final TypeAdapter adapterTag = gson.getDelegateAdapter(this, TypeToken.get(Tag.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfLinkListColumn1Value value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `User` + if (value.getActualInstance() instanceof User) { + element = adapterUser.toJsonTree((User)value.getActualInstance()); + } + // check if the actual instance is of the type `Tag` + if (value.getActualInstance() instanceof Tag) { + element = adapterTag.toJsonTree((Tag)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Tag, User"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize User + try { + // validate the JSON object to see if any exception is thrown + User.validateJsonElement(jsonElement); + AllOfModelArrayAnyOfAllOfLinkListColumn1Value ret = new AllOfModelArrayAnyOfAllOfLinkListColumn1Value(); + ret.setActualInstance(adapterUser.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for User failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'User'", e); + } + + // deserialize Tag + try { + // validate the JSON object to see if any exception is thrown + Tag.validateJsonElement(jsonElement); + AllOfModelArrayAnyOfAllOfLinkListColumn1Value ret = new AllOfModelArrayAnyOfAllOfLinkListColumn1Value(); + ret.setActualInstance(adapterTag.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Tag failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Tag'", e); + } + + + throw new IOException(String.format("Failed deserialization for AllOfModelArrayAnyOfAllOfLinkListColumn1Value: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value() { + super("anyOf", Boolean.FALSE); + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value(User o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value(Tag o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("User", User.class); + schemas.put("Tag", Tag.class); + } + + @Override + public Map> getSchemas() { + return AllOfModelArrayAnyOfAllOfLinkListColumn1Value.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * Tag, User + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(User.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Tag.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Tag, User"); + } + + /** + * Get the actual instance, which can be the following: + * Tag, User + * + * @return The actual instance (Tag, User) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `User`. If the actual instance is not `User`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `User` + * @throws ClassCastException if the instance is not `User` + */ + @SuppressWarnings("unchecked") + public User getUser() throws ClassCastException { + return (User)super.getActualInstance(); + } + + /** + * Get the actual instance of `Tag`. If the actual instance is not `Tag`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Tag` + * @throws ClassCastException if the instance is not `Tag` + */ + @SuppressWarnings("unchecked") + public Tag getTag() throws ClassCastException { + return (Tag)super.getActualInstance(); + } + + + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1Value given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfLinkListColumn1Value + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ + public static AllOfModelArrayAnyOfAllOfLinkListColumn1Value fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfLinkListColumn1Value.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1Value to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToDouble.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToDouble.java new file mode 100644 index 000000000000..89e82c29e68d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToDouble.java @@ -0,0 +1,273 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Object with allOf ref to double + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfRefToDouble { + public static final String SERIALIZED_NAME_HEIGHT = "height"; + @SerializedName(SERIALIZED_NAME_HEIGHT) + @javax.annotation.Nullable + private Double height = 32.1d; + + public AllOfRefToDouble() { + } + + public AllOfRefToDouble height(@javax.annotation.Nullable Double height) { + this.height = height; + return this; + } + + /** + * Height as double + * @return height + */ + @javax.annotation.Nullable + + public Double getHeight() { + return height; + } + + public void setHeight(@javax.annotation.Nullable Double height) { + this.height = height; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfRefToDouble instance itself + */ + public AllOfRefToDouble putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfRefToDouble allOfRefToDouble = (AllOfRefToDouble) o; + return Objects.equals(this.height, allOfRefToDouble.height)&& + Objects.equals(this.additionalProperties, allOfRefToDouble.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(height, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfRefToDouble {\n"); + sb.append(" height: ").append(toIndentedString(height)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("height")); + + // 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 AllOfRefToDouble + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfRefToDouble.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AllOfRefToDouble is not found in the empty JSON string", AllOfRefToDouble.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfRefToDouble.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfRefToDouble' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfRefToDouble.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfRefToDouble value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfRefToDouble read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfRefToDouble instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfRefToDouble given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfRefToDouble + * @throws IOException if the JSON string is invalid with respect to AllOfRefToDouble + */ + public static AllOfRefToDouble fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfRefToDouble.class); + } + + /** + * Convert an instance of AllOfRefToDouble to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToFloat.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToFloat.java new file mode 100644 index 000000000000..4114073966c9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToFloat.java @@ -0,0 +1,273 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Object with allOf ref to float + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfRefToFloat { + public static final String SERIALIZED_NAME_WEIGHT = "weight"; + @SerializedName(SERIALIZED_NAME_WEIGHT) + @javax.annotation.Nullable + private Float weight = 7.89f; + + public AllOfRefToFloat() { + } + + public AllOfRefToFloat weight(@javax.annotation.Nullable Float weight) { + this.weight = weight; + return this; + } + + /** + * Weight as float + * @return weight + */ + @javax.annotation.Nullable + + public Float getWeight() { + return weight; + } + + public void setWeight(@javax.annotation.Nullable Float weight) { + this.weight = weight; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfRefToFloat instance itself + */ + public AllOfRefToFloat putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfRefToFloat allOfRefToFloat = (AllOfRefToFloat) o; + return Objects.equals(this.weight, allOfRefToFloat.weight)&& + Objects.equals(this.additionalProperties, allOfRefToFloat.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(weight, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfRefToFloat {\n"); + sb.append(" weight: ").append(toIndentedString(weight)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("weight")); + + // 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 AllOfRefToFloat + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfRefToFloat.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AllOfRefToFloat is not found in the empty JSON string", AllOfRefToFloat.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfRefToFloat.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfRefToFloat' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfRefToFloat.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfRefToFloat value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfRefToFloat read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfRefToFloat instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfRefToFloat given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfRefToFloat + * @throws IOException if the JSON string is invalid with respect to AllOfRefToFloat + */ + public static AllOfRefToFloat fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfRefToFloat.class); + } + + /** + * Convert an instance of AllOfRefToFloat to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToLong.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToLong.java new file mode 100644 index 000000000000..78207f2c8a3a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AllOfRefToLong.java @@ -0,0 +1,273 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Object with allOf ref to long + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AllOfRefToLong { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id = 10l; + + public AllOfRefToLong() { + } + + public AllOfRefToLong id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Id as long + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfRefToLong instance itself + */ + public AllOfRefToLong putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfRefToLong allOfRefToLong = (AllOfRefToLong) o; + return Objects.equals(this.id, allOfRefToLong.id)&& + Objects.equals(this.additionalProperties, allOfRefToLong.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfRefToLong {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id")); + + // 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 AllOfRefToLong + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfRefToLong.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AllOfRefToLong is not found in the empty JSON string", AllOfRefToLong.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfRefToLong.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfRefToLong' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfRefToLong.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfRefToLong value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfRefToLong read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfRefToLong instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfRefToLong given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfRefToLong + * @throws IOException if the JSON string is invalid with respect to AllOfRefToLong + */ + public static AllOfRefToLong fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfRefToLong.class); + } + + /** + * Convert an instance of AllOfRefToLong to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Animal.java new file mode 100644 index 000000000000..cf4ce3976c18 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Animal.java @@ -0,0 +1,239 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Animal + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Animal { + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + @javax.annotation.Nonnull + protected String className; + + public static final String SERIALIZED_NAME_COLOR = "color"; + @SerializedName(SERIALIZED_NAME_COLOR) + @javax.annotation.Nullable + private String color = "red"; + + public Animal() { + this.className = this.getClass().getSimpleName(); + } + + public Animal className(@javax.annotation.Nonnull String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + */ + @javax.annotation.Nonnull + + public String getClassName() { + return className; + } + + public void setClassName(@javax.annotation.Nonnull String className) { + this.className = className; + } + + + public Animal color(@javax.annotation.Nullable String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + */ + @javax.annotation.Nullable + + public String getColor() { + return color; + } + + public void setColor(@javax.annotation.Nullable String color) { + this.color = color; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Animal instance itself + */ + public Animal putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color)&& + Objects.equals(this.additionalProperties, animal.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(className, color, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("className", "color")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("className")); + } + + /** + * 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 Animal + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Animal.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Animal is not found in the empty JSON string", Animal.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + String discriminatorValue = jsonElement.getAsJsonObject().get("className").getAsString(); + switch (discriminatorValue) { + case "Cat": + Cat.validateJsonElement(jsonElement); + break; + case "Dog": + Dog.validateJsonElement(jsonElement); + break; + default: + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The value of the `className` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue)); + } + } + + + /** + * Create an instance of Animal given an JSON string + * + * @param jsonString JSON string + * @return An instance of Animal + * @throws IOException if the JSON string is invalid with respect to Animal + */ + public static Animal fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Animal.class); + } + + /** + * Convert an instance of Animal to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Apple.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Apple.java new file mode 100644 index 000000000000..6b781bfa23d7 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Apple.java @@ -0,0 +1,306 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Apple + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Apple { + public static final String SERIALIZED_NAME_CULTIVAR = "cultivar"; + @SerializedName(SERIALIZED_NAME_CULTIVAR) + @javax.annotation.Nullable + private String cultivar; + + public static final String SERIALIZED_NAME_ORIGIN = "origin"; + @SerializedName(SERIALIZED_NAME_ORIGIN) + @javax.annotation.Nullable + private String origin; + + public Apple() { + } + + public Apple cultivar(@javax.annotation.Nullable String cultivar) { + this.cultivar = cultivar; + return this; + } + + /** + * Get cultivar + * @return cultivar + */ + @javax.annotation.Nullable + + public String getCultivar() { + return cultivar; + } + + public void setCultivar(@javax.annotation.Nullable String cultivar) { + this.cultivar = cultivar; + } + + + public Apple origin(@javax.annotation.Nullable String origin) { + this.origin = origin; + return this; + } + + /** + * Get origin + * @return origin + */ + @javax.annotation.Nullable + + public String getOrigin() { + return origin; + } + + public void setOrigin(@javax.annotation.Nullable String origin) { + this.origin = origin; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Apple instance itself + */ + public Apple putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Apple apple = (Apple) o; + return Objects.equals(this.cultivar, apple.cultivar) && + Objects.equals(this.origin, apple.origin)&& + Objects.equals(this.additionalProperties, apple.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(cultivar, origin, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Apple {\n"); + sb.append(" cultivar: ").append(toIndentedString(cultivar)).append("\n"); + sb.append(" origin: ").append(toIndentedString(origin)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("cultivar", "origin")); + + // 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 Apple + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Apple.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Apple is not found in the empty JSON string", Apple.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("cultivar") != null && !jsonObj.get("cultivar").isJsonNull()) && !jsonObj.get("cultivar").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `cultivar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("cultivar").toString())); + } + if ((jsonObj.get("origin") != null && !jsonObj.get("origin").isJsonNull()) && !jsonObj.get("origin").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `origin` to be a primitive type in the JSON string but got `%s`", jsonObj.get("origin").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Apple.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Apple' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Apple.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Apple value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Apple read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Apple instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Apple given an JSON string + * + * @param jsonString JSON string + * @return An instance of Apple + * @throws IOException if the JSON string is invalid with respect to Apple + */ + public static Apple fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Apple.class); + } + + /** + * Convert an instance of Apple to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AppleReq.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AppleReq.java new file mode 100644 index 000000000000..f080491ec7a9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/AppleReq.java @@ -0,0 +1,225 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * AppleReq + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class AppleReq { + public static final String SERIALIZED_NAME_CULTIVAR = "cultivar"; + @SerializedName(SERIALIZED_NAME_CULTIVAR) + @javax.annotation.Nonnull + private String cultivar; + + public static final String SERIALIZED_NAME_MEALY = "mealy"; + @SerializedName(SERIALIZED_NAME_MEALY) + @javax.annotation.Nullable + private Boolean mealy; + + public AppleReq() { + } + + public AppleReq cultivar(@javax.annotation.Nonnull String cultivar) { + this.cultivar = cultivar; + return this; + } + + /** + * Get cultivar + * @return cultivar + */ + @javax.annotation.Nonnull + + public String getCultivar() { + return cultivar; + } + + public void setCultivar(@javax.annotation.Nonnull String cultivar) { + this.cultivar = cultivar; + } + + + public AppleReq mealy(@javax.annotation.Nullable Boolean mealy) { + this.mealy = mealy; + return this; + } + + /** + * Get mealy + * @return mealy + */ + @javax.annotation.Nullable + + public Boolean getMealy() { + return mealy; + } + + public void setMealy(@javax.annotation.Nullable Boolean mealy) { + this.mealy = mealy; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AppleReq appleReq = (AppleReq) o; + return Objects.equals(this.cultivar, appleReq.cultivar) && + Objects.equals(this.mealy, appleReq.mealy); + } + + @Override + public int hashCode() { + return Objects.hash(cultivar, mealy); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AppleReq {\n"); + sb.append(" cultivar: ").append(toIndentedString(cultivar)).append("\n"); + sb.append(" mealy: ").append(toIndentedString(mealy)).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) { + return o == null ? "null" : 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("cultivar", "mealy")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("cultivar")); + } + + /** + * 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 AppleReq + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AppleReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in AppleReq is not found in the empty JSON string", AppleReq.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!AppleReq.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` in the JSON string is not defined in the `AppleReq` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AppleReq.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("cultivar").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `cultivar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("cultivar").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AppleReq.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AppleReq' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AppleReq.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AppleReq value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AppleReq read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AppleReq given an JSON string + * + * @param jsonString JSON string + * @return An instance of AppleReq + * @throws IOException if the JSON string is invalid with respect to AppleReq + */ + public static AppleReq fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AppleReq.class); + } + + /** + * Convert an instance of AppleReq to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayAnyOf.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayAnyOf.java new file mode 100644 index 000000000000..4eac0a2e5af0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayAnyOf.java @@ -0,0 +1,387 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayAnyOf extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ArrayAnyOf.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayAnyOf instance itself + */ + public ArrayAnyOf putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(ArrayAnyOf instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched anyOf schema. + */ + private static void writeUnconsumedProperties(ArrayAnyOf value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 ArrayAnyOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + } + + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for ArrayAnyOf: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayAnyOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayAnyOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); + final Type typeInstanceListString = new TypeToken>(){}.getType(); + final TypeAdapter> adapterListString = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceListString)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayAnyOf value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Integer` + if (value.getActualInstance() instanceof Integer) { + element = adapterInteger.toJsonTree((Integer)value.getActualInstance()); + } + // check if the actual instance is of the type `List` + if (value.getActualInstance() instanceof List) { + element = adapterListString.toJsonTree((List)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Integer, List"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public ArrayAnyOf read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize Integer + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + ArrayAnyOf ret = new ArrayAnyOf(); + ret.setActualInstance(adapterInteger.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Integer'", e); + } + + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + ArrayAnyOf ret = new ArrayAnyOf(); + ret.setActualInstance(adapterListString.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'List'", e); + } + + + throw new IOException(String.format("Failed deserialization for ArrayAnyOf: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public ArrayAnyOf() { + super("anyOf", Boolean.FALSE); + } + + public ArrayAnyOf(Integer o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public ArrayAnyOf(List o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Integer", Integer.class); + schemas.put("List", List.class); + } + + @Override + public Map> getSchemas() { + return ArrayAnyOf.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * Integer, List + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Integer.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(List.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Integer, List"); + } + + /** + * Get the actual instance, which can be the following: + * Integer, List + * + * @return The actual instance (Integer, List) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Integer`. If the actual instance is not `Integer`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Integer` + * @throws ClassCastException if the instance is not `Integer` + */ + @SuppressWarnings("unchecked") + public Integer getInteger() throws ClassCastException { + return (Integer)super.getActualInstance(); + } + + /** + * Get the actual instance of `List`. If the actual instance is not `List`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `List` + * @throws ClassCastException if the instance is not `List` + */ + @SuppressWarnings("unchecked") + public List getListString() throws ClassCastException { + return (List)super.getActualInstance(); + } + + + + /** + * Create an instance of ArrayAnyOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayAnyOf + * @throws IOException if the JSON string is invalid with respect to ArrayAnyOf + */ + public static ArrayAnyOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayAnyOf.class); + } + + /** + * Convert an instance of ArrayAnyOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayDefault.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayDefault.java new file mode 100644 index 000000000000..280c2701cff6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayDefault.java @@ -0,0 +1,325 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ArrayDefault + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayDefault { + public static final String SERIALIZED_NAME_WITH_DEFAULT_EMPTY_BRACKET = "WithDefaultEmptyBracket"; + @SerializedName(SERIALIZED_NAME_WITH_DEFAULT_EMPTY_BRACKET) + @javax.annotation.Nullable + private List withDefaultEmptyBracket = new ArrayList<>(); + + public static final String SERIALIZED_NAME_WITHOUT_DEFAULT = "WithoutDefault"; + @SerializedName(SERIALIZED_NAME_WITHOUT_DEFAULT) + @javax.annotation.Nullable + private List withoutDefault = new ArrayList<>(); + + public ArrayDefault() { + } + + public ArrayDefault withDefaultEmptyBracket(@javax.annotation.Nullable List withDefaultEmptyBracket) { + this.withDefaultEmptyBracket = withDefaultEmptyBracket; + return this; + } + + public ArrayDefault addWithDefaultEmptyBracketItem(String withDefaultEmptyBracketItem) { + if (this.withDefaultEmptyBracket == null) { + this.withDefaultEmptyBracket = new ArrayList<>(); + } + this.withDefaultEmptyBracket.add(withDefaultEmptyBracketItem); + return this; + } + + /** + * Get withDefaultEmptyBracket + * @return withDefaultEmptyBracket + */ + @javax.annotation.Nullable + + public List getWithDefaultEmptyBracket() { + return withDefaultEmptyBracket; + } + + public void setWithDefaultEmptyBracket(@javax.annotation.Nullable List withDefaultEmptyBracket) { + this.withDefaultEmptyBracket = withDefaultEmptyBracket; + } + + + public ArrayDefault withoutDefault(@javax.annotation.Nullable List withoutDefault) { + this.withoutDefault = withoutDefault; + return this; + } + + public ArrayDefault addWithoutDefaultItem(String withoutDefaultItem) { + if (this.withoutDefault == null) { + this.withoutDefault = new ArrayList<>(); + } + this.withoutDefault.add(withoutDefaultItem); + return this; + } + + /** + * Get withoutDefault + * @return withoutDefault + */ + @javax.annotation.Nullable + + public List getWithoutDefault() { + return withoutDefault; + } + + public void setWithoutDefault(@javax.annotation.Nullable List withoutDefault) { + this.withoutDefault = withoutDefault; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayDefault instance itself + */ + public ArrayDefault putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayDefault arrayDefault = (ArrayDefault) o; + return Objects.equals(this.withDefaultEmptyBracket, arrayDefault.withDefaultEmptyBracket) && + Objects.equals(this.withoutDefault, arrayDefault.withoutDefault)&& + Objects.equals(this.additionalProperties, arrayDefault.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(withDefaultEmptyBracket, withoutDefault, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayDefault {\n"); + sb.append(" withDefaultEmptyBracket: ").append(toIndentedString(withDefaultEmptyBracket)).append("\n"); + sb.append(" withoutDefault: ").append(toIndentedString(withoutDefault)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("WithDefaultEmptyBracket", "WithoutDefault")); + + // 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 ArrayDefault + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ArrayDefault.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ArrayDefault is not found in the empty JSON string", ArrayDefault.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("WithDefaultEmptyBracket") != null && !jsonObj.get("WithDefaultEmptyBracket").isJsonNull() && !jsonObj.get("WithDefaultEmptyBracket").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `WithDefaultEmptyBracket` to be an array in the JSON string but got `%s`", jsonObj.get("WithDefaultEmptyBracket").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("WithoutDefault") != null && !jsonObj.get("WithoutDefault").isJsonNull() && !jsonObj.get("WithoutDefault").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `WithoutDefault` to be an array in the JSON string but got `%s`", jsonObj.get("WithoutDefault").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayDefault.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayDefault' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayDefault.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayDefault value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ArrayDefault read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ArrayDefault instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayDefault given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayDefault + * @throws IOException if the JSON string is invalid with respect to ArrayDefault + */ + public static ArrayDefault fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayDefault.class); + } + + /** + * Convert an instance of ArrayDefault to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 000000000000..1b8969d75537 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,287 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ArrayOfArrayOfNumberOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayOfArrayOfNumberOnly { + public static final String SERIALIZED_NAME_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; + @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) + @javax.annotation.Nullable + private List> arrayArrayNumber = new ArrayList<>(); + + public ArrayOfArrayOfNumberOnly() { + } + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(@javax.annotation.Nullable List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + if (this.arrayArrayNumber == null) { + this.arrayArrayNumber = new ArrayList<>(); + } + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + */ + @javax.annotation.Nullable + + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + public void setArrayArrayNumber(@javax.annotation.Nullable List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayOfArrayOfNumberOnly instance itself + */ + public ArrayOfArrayOfNumberOnly putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber)&& + Objects.equals(this.additionalProperties, arrayOfArrayOfNumberOnly.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("ArrayArrayNumber")); + + // 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 ArrayOfArrayOfNumberOnly + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ArrayOfArrayOfNumberOnly is not found in the empty JSON string", ArrayOfArrayOfNumberOnly.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("ArrayArrayNumber") != null && !jsonObj.get("ArrayArrayNumber").isJsonNull() && !jsonObj.get("ArrayArrayNumber").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `ArrayArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayArrayNumber").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfArrayOfNumberOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfArrayOfNumberOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfArrayOfNumberOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfArrayOfNumberOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfArrayOfNumberOnly read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ArrayOfArrayOfNumberOnly instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayOfArrayOfNumberOnly given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfArrayOfNumberOnly + * @throws IOException if the JSON string is invalid with respect to ArrayOfArrayOfNumberOnly + */ + public static ArrayOfArrayOfNumberOnly fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfArrayOfNumberOnly.class); + } + + /** + * Convert an instance of ArrayOfArrayOfNumberOnly to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java new file mode 100644 index 000000000000..f45ecdd1098c --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java @@ -0,0 +1,360 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ArrayOfInlineAllOf + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayOfInlineAllOf { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_ARRAY_ALLOF_DOG_PROPERTY = "array_allof_dog_property"; + @SerializedName(SERIALIZED_NAME_ARRAY_ALLOF_DOG_PROPERTY) + @javax.annotation.Nullable + private List arrayAllofDogProperty = new ArrayList<>(); + + public ArrayOfInlineAllOf() { + } + + public ArrayOfInlineAllOf id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public ArrayOfInlineAllOf name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public ArrayOfInlineAllOf arrayAllofDogProperty(@javax.annotation.Nullable List arrayAllofDogProperty) { + this.arrayAllofDogProperty = arrayAllofDogProperty; + return this; + } + + public ArrayOfInlineAllOf addArrayAllofDogPropertyItem(ArrayOfInlineAllOfArrayAllofDogPropertyInner arrayAllofDogPropertyItem) { + if (this.arrayAllofDogProperty == null) { + this.arrayAllofDogProperty = new ArrayList<>(); + } + this.arrayAllofDogProperty.add(arrayAllofDogPropertyItem); + return this; + } + + /** + * Get arrayAllofDogProperty + * @return arrayAllofDogProperty + */ + @javax.annotation.Nullable + + public List getArrayAllofDogProperty() { + return arrayAllofDogProperty; + } + + public void setArrayAllofDogProperty(@javax.annotation.Nullable List arrayAllofDogProperty) { + this.arrayAllofDogProperty = arrayAllofDogProperty; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayOfInlineAllOf instance itself + */ + public ArrayOfInlineAllOf putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfInlineAllOf arrayOfInlineAllOf = (ArrayOfInlineAllOf) o; + return Objects.equals(this.id, arrayOfInlineAllOf.id) && + Objects.equals(this.name, arrayOfInlineAllOf.name) && + Objects.equals(this.arrayAllofDogProperty, arrayOfInlineAllOf.arrayAllofDogProperty)&& + Objects.equals(this.additionalProperties, arrayOfInlineAllOf.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, arrayAllofDogProperty, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfInlineAllOf {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" arrayAllofDogProperty: ").append(toIndentedString(arrayAllofDogProperty)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name", "array_allof_dog_property")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name")); + } + + /** + * 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 ArrayOfInlineAllOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ArrayOfInlineAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ArrayOfInlineAllOf is not found in the empty JSON string", ArrayOfInlineAllOf.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ArrayOfInlineAllOf.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + if (jsonObj.get("array_allof_dog_property") != null && !jsonObj.get("array_allof_dog_property").isJsonNull()) { + com.google.gson.JsonArray jsonArrayarrayAllofDogProperty = jsonObj.getAsJsonArray("array_allof_dog_property"); + if (jsonArrayarrayAllofDogProperty != null) { + // ensure the json data is an array + if (!jsonObj.get("array_allof_dog_property").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_allof_dog_property` to be an array in the JSON string but got `%s`", jsonObj.get("array_allof_dog_property").toString())); + } + + // validate the optional field `array_allof_dog_property` (array) + for (int i = 0; i < jsonArrayarrayAllofDogProperty.size(); i++) { + ArrayOfInlineAllOfArrayAllofDogPropertyInner.validateJsonElement(jsonArrayarrayAllofDogProperty.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfInlineAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfInlineAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfInlineAllOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfInlineAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfInlineAllOf read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ArrayOfInlineAllOf instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayOfInlineAllOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfInlineAllOf + * @throws IOException if the JSON string is invalid with respect to ArrayOfInlineAllOf + */ + public static ArrayOfInlineAllOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfInlineAllOf.class); + } + + /** + * Convert an instance of ArrayOfInlineAllOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java new file mode 100644 index 000000000000..9a943b847014 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java @@ -0,0 +1,306 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ArrayOfInlineAllOfArrayAllofDogPropertyInner + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayOfInlineAllOfArrayAllofDogPropertyInner { + public static final String SERIALIZED_NAME_BREED = "breed"; + @SerializedName(SERIALIZED_NAME_BREED) + @javax.annotation.Nullable + private String breed; + + public static final String SERIALIZED_NAME_COLOR = "color"; + @SerializedName(SERIALIZED_NAME_COLOR) + @javax.annotation.Nullable + private String color; + + public ArrayOfInlineAllOfArrayAllofDogPropertyInner() { + } + + public ArrayOfInlineAllOfArrayAllofDogPropertyInner breed(@javax.annotation.Nullable String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + */ + @javax.annotation.Nullable + + public String getBreed() { + return breed; + } + + public void setBreed(@javax.annotation.Nullable String breed) { + this.breed = breed; + } + + + public ArrayOfInlineAllOfArrayAllofDogPropertyInner color(@javax.annotation.Nullable String color) { + this.color = color; + return this; + } + + /** + * Get color + * @return color + */ + @javax.annotation.Nullable + + public String getColor() { + return color; + } + + public void setColor(@javax.annotation.Nullable String color) { + this.color = color; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayOfInlineAllOfArrayAllofDogPropertyInner instance itself + */ + public ArrayOfInlineAllOfArrayAllofDogPropertyInner putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfInlineAllOfArrayAllofDogPropertyInner arrayOfInlineAllOfArrayAllofDogPropertyInner = (ArrayOfInlineAllOfArrayAllofDogPropertyInner) o; + return Objects.equals(this.breed, arrayOfInlineAllOfArrayAllofDogPropertyInner.breed) && + Objects.equals(this.color, arrayOfInlineAllOfArrayAllofDogPropertyInner.color)&& + Objects.equals(this.additionalProperties, arrayOfInlineAllOfArrayAllofDogPropertyInner.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(breed, color, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfInlineAllOfArrayAllofDogPropertyInner {\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("breed", "color")); + + // 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 ArrayOfInlineAllOfArrayAllofDogPropertyInner + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ArrayOfInlineAllOfArrayAllofDogPropertyInner is not found in the empty JSON string", ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonNull()) && !jsonObj.get("breed").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `breed` to be a primitive type in the JSON string but got `%s`", jsonObj.get("breed").toString())); + } + if ((jsonObj.get("color") != null && !jsonObj.get("color").isJsonNull()) && !jsonObj.get("color").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `color` to be a primitive type in the JSON string but got `%s`", jsonObj.get("color").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfInlineAllOfArrayAllofDogPropertyInner.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfInlineAllOfArrayAllofDogPropertyInner' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfInlineAllOfArrayAllofDogPropertyInner.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfInlineAllOfArrayAllofDogPropertyInner value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfInlineAllOfArrayAllofDogPropertyInner read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ArrayOfInlineAllOfArrayAllofDogPropertyInner instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayOfInlineAllOfArrayAllofDogPropertyInner given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfInlineAllOfArrayAllofDogPropertyInner + * @throws IOException if the JSON string is invalid with respect to ArrayOfInlineAllOfArrayAllofDogPropertyInner + */ + public static ArrayOfInlineAllOfArrayAllofDogPropertyInner fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfInlineAllOfArrayAllofDogPropertyInner.class); + } + + /** + * Convert an instance of ArrayOfInlineAllOfArrayAllofDogPropertyInner to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java new file mode 100644 index 000000000000..aa035fad4f9d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,287 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ArrayOfNumberOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayOfNumberOnly { + public static final String SERIALIZED_NAME_ARRAY_NUMBER = "ArrayNumber"; + @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) + @javax.annotation.Nullable + private List arrayNumber = new ArrayList<>(); + + public ArrayOfNumberOnly() { + } + + public ArrayOfNumberOnly arrayNumber(@javax.annotation.Nullable List arrayNumber) { + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + if (this.arrayNumber == null) { + this.arrayNumber = new ArrayList<>(); + } + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + */ + @javax.annotation.Nullable + + public List getArrayNumber() { + return arrayNumber; + } + + public void setArrayNumber(@javax.annotation.Nullable List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayOfNumberOnly instance itself + */ + public ArrayOfNumberOnly putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber)&& + Objects.equals(this.additionalProperties, arrayOfNumberOnly.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("ArrayNumber")); + + // 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 ArrayOfNumberOnly + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ArrayOfNumberOnly is not found in the empty JSON string", ArrayOfNumberOnly.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("ArrayNumber") != null && !jsonObj.get("ArrayNumber").isJsonNull() && !jsonObj.get("ArrayNumber").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `ArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayNumber").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfNumberOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfNumberOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfNumberOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfNumberOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfNumberOnly read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ArrayOfNumberOnly instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayOfNumberOnly given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOfNumberOnly + * @throws IOException if the JSON string is invalid with respect to ArrayOfNumberOnly + */ + public static ArrayOfNumberOnly fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOfNumberOnly.class); + } + + /** + * Convert an instance of ArrayOfNumberOnly to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOneOf.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOneOf.java new file mode 100644 index 000000000000..058610d72ddb --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayOneOf.java @@ -0,0 +1,393 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayOneOf extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ArrayOneOf.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayOneOf instance itself + */ + public ArrayOneOf putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(ArrayOneOf instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(ArrayOneOf value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 ArrayOneOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize Integer + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + } + + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for ArrayOneOf: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOneOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOneOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); + final Type typeInstanceListString = new TypeToken>(){}.getType(); + final TypeAdapter> adapterListString = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceListString)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOneOf value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Integer` + if (value.getActualInstance() instanceof Integer) { + element = adapterInteger.toJsonTree((Integer)value.getActualInstance()); + } + // check if the actual instance is of the type `List` + if (value.getActualInstance() instanceof List) { + element = adapterListString.toJsonTree((List)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Integer, List"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public ArrayOneOf read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Integer + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterInteger; + match++; + log.log(Level.FINER, "Input data matches schema 'Integer'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Integer'", e); + } + + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + actualAdapter = adapterListString; + match++; + log.log(Level.FINER, "Input data matches schema 'List'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'List'", e); + } + + if (match == 1) { + ArrayOneOf ret = new ArrayOneOf(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for ArrayOneOf: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public ArrayOneOf() { + super("oneOf", Boolean.FALSE); + } + + public ArrayOneOf(Integer o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public ArrayOneOf(List o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Integer", Integer.class); + schemas.put("List", List.class); + } + + @Override + public Map> getSchemas() { + return ArrayOneOf.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Integer, List + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Integer.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(List.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Integer, List"); + } + + /** + * Get the actual instance, which can be the following: + * Integer, List + * + * @return The actual instance (Integer, List) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Integer`. If the actual instance is not `Integer`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Integer` + * @throws ClassCastException if the instance is not `Integer` + */ + @SuppressWarnings("unchecked") + public Integer getInteger() throws ClassCastException { + return (Integer)super.getActualInstance(); + } + + /** + * Get the actual instance of `List`. If the actual instance is not `List`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `List` + * @throws ClassCastException if the instance is not `List` + */ + @SuppressWarnings("unchecked") + public List getListString() throws ClassCastException { + return (List)super.getActualInstance(); + } + + + + /** + * Create an instance of ArrayOneOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayOneOf + * @throws IOException if the JSON string is invalid with respect to ArrayOneOf + */ + public static ArrayOneOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayOneOf.class); + } + + /** + * Convert an instance of ArrayOneOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayTest.java new file mode 100644 index 000000000000..323d7a81bdfc --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -0,0 +1,364 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ArrayTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ArrayTest { + public static final String SERIALIZED_NAME_ARRAY_OF_STRING = "array_of_string"; + @SerializedName(SERIALIZED_NAME_ARRAY_OF_STRING) + @javax.annotation.Nullable + private List arrayOfString = new ArrayList<>(); + + public static final String SERIALIZED_NAME_ARRAY_ARRAY_OF_INTEGER = "array_array_of_integer"; + @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_INTEGER) + @javax.annotation.Nullable + private List> arrayArrayOfInteger = new ArrayList<>(); + + public static final String SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; + @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) + @javax.annotation.Nullable + private List> arrayArrayOfModel = new ArrayList<>(); + + public ArrayTest() { + } + + public ArrayTest arrayOfString(@javax.annotation.Nullable List arrayOfString) { + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + if (this.arrayOfString == null) { + this.arrayOfString = new ArrayList<>(); + } + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + */ + @javax.annotation.Nullable + + public List getArrayOfString() { + return arrayOfString; + } + + public void setArrayOfString(@javax.annotation.Nullable List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + + public ArrayTest arrayArrayOfInteger(@javax.annotation.Nullable List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + if (this.arrayArrayOfInteger == null) { + this.arrayArrayOfInteger = new ArrayList<>(); + } + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + */ + @javax.annotation.Nullable + + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + public void setArrayArrayOfInteger(@javax.annotation.Nullable List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + + public ArrayTest arrayArrayOfModel(@javax.annotation.Nullable List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + if (this.arrayArrayOfModel == null) { + this.arrayArrayOfModel = new ArrayList<>(); + } + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + */ + @javax.annotation.Nullable + + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + public void setArrayArrayOfModel(@javax.annotation.Nullable List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ArrayTest instance itself + */ + public ArrayTest putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel)&& + Objects.equals(this.additionalProperties, arrayTest.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("array_of_string", "array_array_of_integer", "array_array_of_model")); + + // 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 ArrayTest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ArrayTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ArrayTest is not found in the empty JSON string", ArrayTest.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("array_of_string") != null && !jsonObj.get("array_of_string").isJsonNull() && !jsonObj.get("array_of_string").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_of_string` to be an array in the JSON string but got `%s`", jsonObj.get("array_of_string").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("array_array_of_integer") != null && !jsonObj.get("array_array_of_integer").isJsonNull() && !jsonObj.get("array_array_of_integer").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_array_of_integer` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_integer").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("array_array_of_model") != null && !jsonObj.get("array_array_of_model").isJsonNull() && !jsonObj.get("array_array_of_model").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_array_of_model` to be an array in the JSON string but got `%s`", jsonObj.get("array_array_of_model").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ArrayTest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ArrayTest instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ArrayTest given an JSON string + * + * @param jsonString JSON string + * @return An instance of ArrayTest + * @throws IOException if the JSON string is invalid with respect to ArrayTest + */ + public static ArrayTest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ArrayTest.class); + } + + /** + * Convert an instance of ArrayTest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Banana.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Banana.java new file mode 100644 index 000000000000..7d426e0270b1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Banana.java @@ -0,0 +1,274 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Banana + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Banana { + public static final String SERIALIZED_NAME_LENGTH_CM = "lengthCm"; + @SerializedName(SERIALIZED_NAME_LENGTH_CM) + @javax.annotation.Nullable + private BigDecimal lengthCm; + + public Banana() { + } + + public Banana lengthCm(@javax.annotation.Nullable BigDecimal lengthCm) { + this.lengthCm = lengthCm; + return this; + } + + /** + * Get lengthCm + * @return lengthCm + */ + @javax.annotation.Nullable + + public BigDecimal getLengthCm() { + return lengthCm; + } + + public void setLengthCm(@javax.annotation.Nullable BigDecimal lengthCm) { + this.lengthCm = lengthCm; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Banana instance itself + */ + public Banana putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Banana banana = (Banana) o; + return Objects.equals(this.lengthCm, banana.lengthCm)&& + Objects.equals(this.additionalProperties, banana.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(lengthCm, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Banana {\n"); + sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("lengthCm")); + + // 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 Banana + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Banana.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Banana is not found in the empty JSON string", Banana.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Banana.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Banana' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Banana.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Banana value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Banana read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Banana instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Banana given an JSON string + * + * @param jsonString JSON string + * @return An instance of Banana + * @throws IOException if the JSON string is invalid with respect to Banana + */ + public static Banana fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Banana.class); + } + + /** + * Convert an instance of Banana to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/BananaReq.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/BananaReq.java new file mode 100644 index 000000000000..b4daa8ddc1a0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/BananaReq.java @@ -0,0 +1,223 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * BananaReq + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class BananaReq { + public static final String SERIALIZED_NAME_LENGTH_CM = "lengthCm"; + @SerializedName(SERIALIZED_NAME_LENGTH_CM) + @javax.annotation.Nonnull + private BigDecimal lengthCm; + + public static final String SERIALIZED_NAME_SWEET = "sweet"; + @SerializedName(SERIALIZED_NAME_SWEET) + @javax.annotation.Nullable + private Boolean sweet; + + public BananaReq() { + } + + public BananaReq lengthCm(@javax.annotation.Nonnull BigDecimal lengthCm) { + this.lengthCm = lengthCm; + return this; + } + + /** + * Get lengthCm + * @return lengthCm + */ + @javax.annotation.Nonnull + + public BigDecimal getLengthCm() { + return lengthCm; + } + + public void setLengthCm(@javax.annotation.Nonnull BigDecimal lengthCm) { + this.lengthCm = lengthCm; + } + + + public BananaReq sweet(@javax.annotation.Nullable Boolean sweet) { + this.sweet = sweet; + return this; + } + + /** + * Get sweet + * @return sweet + */ + @javax.annotation.Nullable + + public Boolean getSweet() { + return sweet; + } + + public void setSweet(@javax.annotation.Nullable Boolean sweet) { + this.sweet = sweet; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BananaReq bananaReq = (BananaReq) o; + return Objects.equals(this.lengthCm, bananaReq.lengthCm) && + Objects.equals(this.sweet, bananaReq.sweet); + } + + @Override + public int hashCode() { + return Objects.hash(lengthCm, sweet); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BananaReq {\n"); + sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); + sb.append(" sweet: ").append(toIndentedString(sweet)).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) { + return o == null ? "null" : 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("lengthCm", "sweet")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("lengthCm")); + } + + /** + * 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 BananaReq + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!BananaReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in BananaReq is not found in the empty JSON string", BananaReq.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!BananaReq.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` in the JSON string is not defined in the `BananaReq` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : BananaReq.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!BananaReq.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'BananaReq' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(BananaReq.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, BananaReq value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public BananaReq read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of BananaReq given an JSON string + * + * @param jsonString JSON string + * @return An instance of BananaReq + * @throws IOException if the JSON string is invalid with respect to BananaReq + */ + public static BananaReq fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, BananaReq.class); + } + + /** + * Convert an instance of BananaReq to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/BasquePig.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/BasquePig.java new file mode 100644 index 000000000000..0af4157d552a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/BasquePig.java @@ -0,0 +1,283 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * BasquePig + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class BasquePig { + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + @javax.annotation.Nonnull + private String className; + + public BasquePig() { + } + + public BasquePig className(@javax.annotation.Nonnull String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + */ + @javax.annotation.Nonnull + + public String getClassName() { + return className; + } + + public void setClassName(@javax.annotation.Nonnull String className) { + this.className = className; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the BasquePig instance itself + */ + public BasquePig putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BasquePig basquePig = (BasquePig) o; + return Objects.equals(this.className, basquePig.className)&& + Objects.equals(this.additionalProperties, basquePig.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(className, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BasquePig {\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("className")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("className")); + } + + /** + * 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 BasquePig + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!BasquePig.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in BasquePig is not found in the empty JSON string", BasquePig.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : BasquePig.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("className").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!BasquePig.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'BasquePig' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(BasquePig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, BasquePig value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public BasquePig read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + BasquePig instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of BasquePig given an JSON string + * + * @param jsonString JSON string + * @return An instance of BasquePig + * @throws IOException if the JSON string is invalid with respect to BasquePig + */ + public static BasquePig fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, BasquePig.class); + } + + /** + * Convert an instance of BasquePig to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Capitalization.java new file mode 100644 index 000000000000..bb007fd9b336 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Capitalization.java @@ -0,0 +1,426 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Capitalization + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Capitalization { + public static final String SERIALIZED_NAME_SMALL_CAMEL = "smallCamel"; + @SerializedName(SERIALIZED_NAME_SMALL_CAMEL) + @javax.annotation.Nullable + private String smallCamel; + + public static final String SERIALIZED_NAME_CAPITAL_CAMEL = "CapitalCamel"; + @SerializedName(SERIALIZED_NAME_CAPITAL_CAMEL) + @javax.annotation.Nullable + private String capitalCamel; + + public static final String SERIALIZED_NAME_SMALL_SNAKE = "small_Snake"; + @SerializedName(SERIALIZED_NAME_SMALL_SNAKE) + @javax.annotation.Nullable + private String smallSnake; + + public static final String SERIALIZED_NAME_CAPITAL_SNAKE = "Capital_Snake"; + @SerializedName(SERIALIZED_NAME_CAPITAL_SNAKE) + @javax.annotation.Nullable + private String capitalSnake; + + public static final String SERIALIZED_NAME_SC_A_E_T_H_FLOW_POINTS = "SCA_ETH_Flow_Points"; + @SerializedName(SERIALIZED_NAME_SC_A_E_T_H_FLOW_POINTS) + @javax.annotation.Nullable + private String scAETHFlowPoints; + + public static final String SERIALIZED_NAME_A_T_T_N_A_M_E = "ATT_NAME"; + @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) + @javax.annotation.Nullable + private String ATT_NAME; + + public Capitalization() { + } + + public Capitalization smallCamel(@javax.annotation.Nullable String smallCamel) { + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + */ + @javax.annotation.Nullable + + public String getSmallCamel() { + return smallCamel; + } + + public void setSmallCamel(@javax.annotation.Nullable String smallCamel) { + this.smallCamel = smallCamel; + } + + + public Capitalization capitalCamel(@javax.annotation.Nullable String capitalCamel) { + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + */ + @javax.annotation.Nullable + + public String getCapitalCamel() { + return capitalCamel; + } + + public void setCapitalCamel(@javax.annotation.Nullable String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + + public Capitalization smallSnake(@javax.annotation.Nullable String smallSnake) { + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + */ + @javax.annotation.Nullable + + public String getSmallSnake() { + return smallSnake; + } + + public void setSmallSnake(@javax.annotation.Nullable String smallSnake) { + this.smallSnake = smallSnake; + } + + + public Capitalization capitalSnake(@javax.annotation.Nullable String capitalSnake) { + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + */ + @javax.annotation.Nullable + + public String getCapitalSnake() { + return capitalSnake; + } + + public void setCapitalSnake(@javax.annotation.Nullable String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + + public Capitalization scAETHFlowPoints(@javax.annotation.Nullable String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + */ + @javax.annotation.Nullable + + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + public void setScAETHFlowPoints(@javax.annotation.Nullable String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + + public Capitalization ATT_NAME(@javax.annotation.Nullable String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + */ + @javax.annotation.Nullable + + public String getATTNAME() { + return ATT_NAME; + } + + public void setATTNAME(@javax.annotation.Nullable String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Capitalization instance itself + */ + public Capitalization putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME)&& + Objects.equals(this.additionalProperties, capitalization.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("smallCamel", "CapitalCamel", "small_Snake", "Capital_Snake", "SCA_ETH_Flow_Points", "ATT_NAME")); + + // 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 Capitalization + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Capitalization.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Capitalization is not found in the empty JSON string", Capitalization.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonNull()) && !jsonObj.get("smallCamel").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `smallCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("smallCamel").toString())); + } + if ((jsonObj.get("CapitalCamel") != null && !jsonObj.get("CapitalCamel").isJsonNull()) && !jsonObj.get("CapitalCamel").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `CapitalCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("CapitalCamel").toString())); + } + if ((jsonObj.get("small_Snake") != null && !jsonObj.get("small_Snake").isJsonNull()) && !jsonObj.get("small_Snake").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `small_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("small_Snake").toString())); + } + if ((jsonObj.get("Capital_Snake") != null && !jsonObj.get("Capital_Snake").isJsonNull()) && !jsonObj.get("Capital_Snake").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `Capital_Snake` to be a primitive type in the JSON string but got `%s`", jsonObj.get("Capital_Snake").toString())); + } + if ((jsonObj.get("SCA_ETH_Flow_Points") != null && !jsonObj.get("SCA_ETH_Flow_Points").isJsonNull()) && !jsonObj.get("SCA_ETH_Flow_Points").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `SCA_ETH_Flow_Points` to be a primitive type in the JSON string but got `%s`", jsonObj.get("SCA_ETH_Flow_Points").toString())); + } + if ((jsonObj.get("ATT_NAME") != null && !jsonObj.get("ATT_NAME").isJsonNull()) && !jsonObj.get("ATT_NAME").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `ATT_NAME` to be a primitive type in the JSON string but got `%s`", jsonObj.get("ATT_NAME").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Capitalization.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Capitalization' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Capitalization.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Capitalization value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Capitalization read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Capitalization instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Capitalization given an JSON string + * + * @param jsonString JSON string + * @return An instance of Capitalization + * @throws IOException if the JSON string is invalid with respect to Capitalization + */ + public static Capitalization fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Capitalization.class); + } + + /** + * Convert an instance of Capitalization to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Cat.java new file mode 100644 index 000000000000..5746a610bc96 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Cat.java @@ -0,0 +1,250 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Cat + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Cat extends Animal { + public static final String SERIALIZED_NAME_DECLAWED = "declawed"; + @SerializedName(SERIALIZED_NAME_DECLAWED) + @javax.annotation.Nullable + private Boolean declawed; + + public Cat() { + this.className = this.getClass().getSimpleName(); + } + + public Cat declawed(@javax.annotation.Nullable Boolean declawed) { + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + */ + @javax.annotation.Nullable + + public Boolean getDeclawed() { + return declawed; + } + + public void setDeclawed(@javax.annotation.Nullable Boolean declawed) { + this.declawed = declawed; + } + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * The bag is inherited from the superclass. + * + * @param key name of the property + * @param value value of the property + * @return the Cat instance itself + */ + @Override + public Cat putAdditionalProperty(String key, Object value) { + super.putAdditionalProperty(key, value); + return this; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).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) { + return o == null ? "null" : 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("className", "color", "declawed")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("className")); + } + + /** + * 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 Cat + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Cat.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Cat is not found in the empty JSON string", Cat.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Cat.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Cat.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Cat' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Cat.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Cat value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Cat read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Cat instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Cat given an JSON string + * + * @param jsonString JSON string + * @return An instance of Cat + * @throws IOException if the JSON string is invalid with respect to Cat + */ + public static Cat fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Cat.class); + } + + /** + * Convert an instance of Cat to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 000000000000..92c899e6da6e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,310 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Category + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Category { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name = "default-name"; + + public Category() { + } + + public Category id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Category name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Category instance itself + */ + public Category putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name)&& + Objects.equals(this.additionalProperties, category.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name")); + } + + /** + * 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 Category + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Category.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Category.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Category' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Category.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Category value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Category read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Category instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Category given an JSON string + * + * @param jsonString JSON string + * @return An instance of Category + * @throws IOException if the JSON string is invalid with respect to Category + */ + public static Category fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Category.class); + } + + /** + * Convert an instance of Category to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ClassModel.java new file mode 100644 index 000000000000..d9192c9655f1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ClassModel.java @@ -0,0 +1,276 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Model for testing model with \"_class\" property + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ClassModel { + public static final String SERIALIZED_NAME_PROPERTY_CLASS = "_class"; + @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) + @javax.annotation.Nullable + private String propertyClass; + + public ClassModel() { + } + + public ClassModel propertyClass(@javax.annotation.Nullable String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + */ + @javax.annotation.Nullable + + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(@javax.annotation.Nullable String propertyClass) { + this.propertyClass = propertyClass; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ClassModel instance itself + */ + public ClassModel putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass)&& + Objects.equals(this.additionalProperties, classModel.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("_class")); + + // 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 ClassModel + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ClassModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ClassModel is not found in the empty JSON string", ClassModel.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonNull()) && !jsonObj.get("_class").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `_class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_class").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ClassModel.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ClassModel' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ClassModel.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ClassModel value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ClassModel read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ClassModel instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ClassModel given an JSON string + * + * @param jsonString JSON string + * @return An instance of ClassModel + * @throws IOException if the JSON string is invalid with respect to ClassModel + */ + public static ClassModel fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ClassModel.class); + } + + /** + * Convert an instance of ClassModel to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Client.java new file mode 100644 index 000000000000..6bd2a6bf11a8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Client.java @@ -0,0 +1,276 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Client + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Client { + public static final String SERIALIZED_NAME_CLIENT = "client"; + @SerializedName(SERIALIZED_NAME_CLIENT) + @javax.annotation.Nullable + private String client; + + public Client() { + } + + public Client client(@javax.annotation.Nullable String client) { + this.client = client; + return this; + } + + /** + * Get client + * @return client + */ + @javax.annotation.Nullable + + public String getClient() { + return client; + } + + public void setClient(@javax.annotation.Nullable String client) { + this.client = client; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Client instance itself + */ + public Client putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client)&& + Objects.equals(this.additionalProperties, client.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(client, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("client")); + + // 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 Client + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Client.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Client is not found in the empty JSON string", Client.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("client") != null && !jsonObj.get("client").isJsonNull()) && !jsonObj.get("client").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `client` to be a primitive type in the JSON string but got `%s`", jsonObj.get("client").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Client.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Client' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Client.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Client value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Client read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Client instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Client given an JSON string + * + * @param jsonString JSON string + * @return An instance of Client + * @throws IOException if the JSON string is invalid with respect to Client + */ + public static Client fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Client.class); + } + + /** + * Convert an instance of Client to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java new file mode 100644 index 000000000000..ce17da0a39d8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java @@ -0,0 +1,313 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ComplexQuadrilateral + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ComplexQuadrilateral { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + @javax.annotation.Nonnull + private String shapeType; + + public static final String SERIALIZED_NAME_QUADRILATERAL_TYPE = "quadrilateralType"; + @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) + @javax.annotation.Nonnull + private String quadrilateralType; + + public ComplexQuadrilateral() { + } + + public ComplexQuadrilateral shapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + */ + @javax.annotation.Nonnull + + public String getShapeType() { + return shapeType; + } + + public void setShapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + } + + + public ComplexQuadrilateral quadrilateralType(@javax.annotation.Nonnull String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + return this; + } + + /** + * Get quadrilateralType + * @return quadrilateralType + */ + @javax.annotation.Nonnull + + public String getQuadrilateralType() { + return quadrilateralType; + } + + public void setQuadrilateralType(@javax.annotation.Nonnull String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ComplexQuadrilateral instance itself + */ + public ComplexQuadrilateral putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ComplexQuadrilateral complexQuadrilateral = (ComplexQuadrilateral) o; + return Objects.equals(this.shapeType, complexQuadrilateral.shapeType) && + Objects.equals(this.quadrilateralType, complexQuadrilateral.quadrilateralType)&& + Objects.equals(this.additionalProperties, complexQuadrilateral.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, quadrilateralType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ComplexQuadrilateral {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("shapeType", "quadrilateralType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("shapeType", "quadrilateralType")); + } + + /** + * 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 ComplexQuadrilateral + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ComplexQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ComplexQuadrilateral is not found in the empty JSON string", ComplexQuadrilateral.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ComplexQuadrilateral.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("shapeType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); + } + if (!jsonObj.get("quadrilateralType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `quadrilateralType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("quadrilateralType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ComplexQuadrilateral.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ComplexQuadrilateral' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ComplexQuadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ComplexQuadrilateral value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ComplexQuadrilateral read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ComplexQuadrilateral instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ComplexQuadrilateral given an JSON string + * + * @param jsonString JSON string + * @return An instance of ComplexQuadrilateral + * @throws IOException if the JSON string is invalid with respect to ComplexQuadrilateral + */ + public static ComplexQuadrilateral fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ComplexQuadrilateral.class); + } + + /** + * Convert an instance of ComplexQuadrilateral to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/DanishPig.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/DanishPig.java new file mode 100644 index 000000000000..9049ebf3d375 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/DanishPig.java @@ -0,0 +1,283 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * DanishPig + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class DanishPig { + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + @javax.annotation.Nonnull + private String className; + + public DanishPig() { + } + + public DanishPig className(@javax.annotation.Nonnull String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + */ + @javax.annotation.Nonnull + + public String getClassName() { + return className; + } + + public void setClassName(@javax.annotation.Nonnull String className) { + this.className = className; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the DanishPig instance itself + */ + public DanishPig putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DanishPig danishPig = (DanishPig) o; + return Objects.equals(this.className, danishPig.className)&& + Objects.equals(this.additionalProperties, danishPig.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(className, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DanishPig {\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("className")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("className")); + } + + /** + * 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 DanishPig + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!DanishPig.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in DanishPig is not found in the empty JSON string", DanishPig.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : DanishPig.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("className").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DanishPig.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DanishPig' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DanishPig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DanishPig value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public DanishPig read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + DanishPig instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of DanishPig given an JSON string + * + * @param jsonString JSON string + * @return An instance of DanishPig + * @throws IOException if the JSON string is invalid with respect to DanishPig + */ + public static DanishPig fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DanishPig.class); + } + + /** + * Convert an instance of DanishPig to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/DeprecatedObject.java new file mode 100644 index 000000000000..425f3b7f0d51 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -0,0 +1,278 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * DeprecatedObject + * @deprecated + */ +@Deprecated +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class DeprecatedObject { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nullable + private String name; + + public DeprecatedObject() { + } + + public DeprecatedObject name(@javax.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nullable + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nullable String name) { + this.name = name; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the DeprecatedObject instance itself + */ + public DeprecatedObject putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeprecatedObject deprecatedObject = (DeprecatedObject) o; + return Objects.equals(this.name, deprecatedObject.name)&& + Objects.equals(this.additionalProperties, deprecatedObject.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(name, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeprecatedObject {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("name")); + + // 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 DeprecatedObject + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!DeprecatedObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in DeprecatedObject is not found in the empty JSON string", DeprecatedObject.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DeprecatedObject.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DeprecatedObject' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DeprecatedObject.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DeprecatedObject value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public DeprecatedObject read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + DeprecatedObject instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of DeprecatedObject given an JSON string + * + * @param jsonString JSON string + * @return An instance of DeprecatedObject + * @throws IOException if the JSON string is invalid with respect to DeprecatedObject + */ + public static DeprecatedObject fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, DeprecatedObject.class); + } + + /** + * Convert an instance of DeprecatedObject to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Dog.java new file mode 100644 index 000000000000..c315f28d3b90 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Dog.java @@ -0,0 +1,250 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Dog + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Dog extends Animal { + public static final String SERIALIZED_NAME_BREED = "breed"; + @SerializedName(SERIALIZED_NAME_BREED) + @javax.annotation.Nullable + private String breed; + + public Dog() { + this.className = this.getClass().getSimpleName(); + } + + public Dog breed(@javax.annotation.Nullable String breed) { + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + */ + @javax.annotation.Nullable + + public String getBreed() { + return breed; + } + + public void setBreed(@javax.annotation.Nullable String breed) { + this.breed = breed; + } + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * The bag is inherited from the superclass. + * + * @param key name of the property + * @param value value of the property + * @return the Dog instance itself + */ + @Override + public Dog putAdditionalProperty(String key, Object value) { + super.putAdditionalProperty(key, value); + return this; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).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) { + return o == null ? "null" : 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("className", "color", "breed")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("className")); + } + + /** + * 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 Dog + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Dog.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Dog is not found in the empty JSON string", Dog.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Dog.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Dog.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Dog' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Dog.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Dog value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Dog read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Dog instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Dog given an JSON string + * + * @param jsonString JSON string + * @return An instance of Dog + * @throws IOException if the JSON string is invalid with respect to Dog + */ + public static Dog fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Dog.class); + } + + /** + * Convert an instance of Dog to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Drawing.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Drawing.java new file mode 100644 index 000000000000..81179976c376 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Drawing.java @@ -0,0 +1,389 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Drawing + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Drawing { + public static final String SERIALIZED_NAME_MAIN_SHAPE = "mainShape"; + @SerializedName(SERIALIZED_NAME_MAIN_SHAPE) + @javax.annotation.Nullable + private Shape mainShape; + + public static final String SERIALIZED_NAME_SHAPE_OR_NULL = "shapeOrNull"; + @SerializedName(SERIALIZED_NAME_SHAPE_OR_NULL) + @javax.annotation.Nullable + private ShapeOrNull shapeOrNull; + + public static final String SERIALIZED_NAME_NULLABLE_SHAPE = "nullableShape"; + @SerializedName(SERIALIZED_NAME_NULLABLE_SHAPE) + @javax.annotation.Nullable + private NullableShape nullableShape; + + public static final String SERIALIZED_NAME_SHAPES = "shapes"; + @SerializedName(SERIALIZED_NAME_SHAPES) + @javax.annotation.Nullable + private List shapes = new ArrayList<>(); + + public Drawing() { + } + + public Drawing mainShape(@javax.annotation.Nullable Shape mainShape) { + this.mainShape = mainShape; + return this; + } + + /** + * Get mainShape + * @return mainShape + */ + @javax.annotation.Nullable + + public Shape getMainShape() { + return mainShape; + } + + public void setMainShape(@javax.annotation.Nullable Shape mainShape) { + this.mainShape = mainShape; + } + + + public Drawing shapeOrNull(@javax.annotation.Nullable ShapeOrNull shapeOrNull) { + this.shapeOrNull = shapeOrNull; + return this; + } + + /** + * Get shapeOrNull + * @return shapeOrNull + */ + @javax.annotation.Nullable + + public ShapeOrNull getShapeOrNull() { + return shapeOrNull; + } + + public void setShapeOrNull(@javax.annotation.Nullable ShapeOrNull shapeOrNull) { + this.shapeOrNull = shapeOrNull; + } + + + public Drawing nullableShape(@javax.annotation.Nullable NullableShape nullableShape) { + this.nullableShape = nullableShape; + return this; + } + + /** + * Get nullableShape + * @return nullableShape + */ + @javax.annotation.Nullable + + public NullableShape getNullableShape() { + return nullableShape; + } + + public void setNullableShape(@javax.annotation.Nullable NullableShape nullableShape) { + this.nullableShape = nullableShape; + } + + + public Drawing shapes(@javax.annotation.Nullable List shapes) { + this.shapes = shapes; + return this; + } + + public Drawing addShapesItem(Shape shapesItem) { + if (this.shapes == null) { + this.shapes = new ArrayList<>(); + } + this.shapes.add(shapesItem); + return this; + } + + /** + * Get shapes + * @return shapes + */ + @javax.annotation.Nullable + + public List getShapes() { + return shapes; + } + + public void setShapes(@javax.annotation.Nullable List shapes) { + this.shapes = shapes; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Drawing instance itself + */ + public Drawing putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Drawing drawing = (Drawing) o; + return Objects.equals(this.mainShape, drawing.mainShape) && + Objects.equals(this.shapeOrNull, drawing.shapeOrNull) && + Objects.equals(this.nullableShape, drawing.nullableShape) && + Objects.equals(this.shapes, drawing.shapes)&& + Objects.equals(this.additionalProperties, drawing.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(mainShape, shapeOrNull, nullableShape, shapes, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Drawing {\n"); + sb.append(" mainShape: ").append(toIndentedString(mainShape)).append("\n"); + sb.append(" shapeOrNull: ").append(toIndentedString(shapeOrNull)).append("\n"); + sb.append(" nullableShape: ").append(toIndentedString(nullableShape)).append("\n"); + sb.append(" shapes: ").append(toIndentedString(shapes)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("mainShape", "shapeOrNull", "nullableShape", "shapes")); + + // 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 Drawing + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Drawing.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Drawing is not found in the empty JSON string", Drawing.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `mainShape` + if (jsonObj.get("mainShape") != null && !jsonObj.get("mainShape").isJsonNull()) { + Shape.validateJsonElement(jsonObj.get("mainShape")); + } + // validate the optional field `shapeOrNull` + if (jsonObj.get("shapeOrNull") != null && !jsonObj.get("shapeOrNull").isJsonNull()) { + ShapeOrNull.validateJsonElement(jsonObj.get("shapeOrNull")); + } + // validate the optional field `nullableShape` + if (jsonObj.get("nullableShape") != null && !jsonObj.get("nullableShape").isJsonNull()) { + NullableShape.validateJsonElement(jsonObj.get("nullableShape")); + } + if (jsonObj.get("shapes") != null && !jsonObj.get("shapes").isJsonNull()) { + com.google.gson.JsonArray jsonArrayshapes = jsonObj.getAsJsonArray("shapes"); + if (jsonArrayshapes != null) { + // ensure the json data is an array + if (!jsonObj.get("shapes").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `shapes` to be an array in the JSON string but got `%s`", jsonObj.get("shapes").toString())); + } + + // validate the optional field `shapes` (array) + for (int i = 0; i < jsonArrayshapes.size(); i++) { + Shape.validateJsonElement(jsonArrayshapes.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Drawing.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Drawing' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Drawing.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Drawing value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Drawing read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Drawing instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Drawing given an JSON string + * + * @param jsonString JSON string + * @return An instance of Drawing + * @throws IOException if the JSON string is invalid with respect to Drawing + */ + public static Drawing fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Drawing.class); + } + + /** + * Convert an instance of Drawing to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumArrays.java new file mode 100644 index 000000000000..c5b3290c83ec --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -0,0 +1,425 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * EnumArrays + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + @JsonAdapter(JustSymbolEnum.Adapter.class) + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static JustSymbolEnum fromValue(String value) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final JustSymbolEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public JustSymbolEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return JustSymbolEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + JustSymbolEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_JUST_SYMBOL = "just_symbol"; + @SerializedName(SERIALIZED_NAME_JUST_SYMBOL) + @javax.annotation.Nullable + private JustSymbolEnum justSymbol; + + /** + * Gets or Sets arrayEnum + */ + @JsonAdapter(ArrayEnumEnum.Adapter.class) + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ArrayEnumEnum fromValue(String value) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final ArrayEnumEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public ArrayEnumEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return ArrayEnumEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + ArrayEnumEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_ARRAY_ENUM = "array_enum"; + @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) + @javax.annotation.Nullable + private List arrayEnum = new ArrayList<>(); + + public EnumArrays() { + } + + public EnumArrays justSymbol(@javax.annotation.Nullable JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + */ + @javax.annotation.Nullable + + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + public void setJustSymbol(@javax.annotation.Nullable JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + + public EnumArrays arrayEnum(@javax.annotation.Nullable List arrayEnum) { + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + if (this.arrayEnum == null) { + this.arrayEnum = new ArrayList<>(); + } + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + */ + @javax.annotation.Nullable + + public List getArrayEnum() { + return arrayEnum; + } + + public void setArrayEnum(@javax.annotation.Nullable List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the EnumArrays instance itself + */ + public EnumArrays putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum)&& + Objects.equals(this.additionalProperties, enumArrays.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("just_symbol", "array_enum")); + + // 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 EnumArrays + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!EnumArrays.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in EnumArrays is not found in the empty JSON string", EnumArrays.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString())); + } + // validate the optional field `just_symbol` + if (jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) { + JustSymbolEnum.validateJsonElement(jsonObj.get("just_symbol")); + } + // ensure the optional json data is an array if present + if (jsonObj.get("array_enum") != null && !jsonObj.get("array_enum").isJsonNull() && !jsonObj.get("array_enum").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_enum` to be an array in the JSON string but got `%s`", jsonObj.get("array_enum").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EnumArrays.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EnumArrays' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EnumArrays.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EnumArrays value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public EnumArrays read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + EnumArrays instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of EnumArrays given an JSON string + * + * @param jsonString JSON string + * @return An instance of EnumArrays + * @throws IOException if the JSON string is invalid with respect to EnumArrays + */ + public static EnumArrays fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, EnumArrays.class); + } + + /** + * Convert an instance of EnumArrays to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumClass.java new file mode 100644 index 000000000000..c2dfd3aecd7c --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumClass.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +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; + +/** + * Gets or Sets EnumClass + */ +@JsonAdapter(EnumClass.Adapter.class) +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumClass fromValue(String value) { + for (EnumClass b : EnumClass.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumClass enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumClass read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumClass.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumClass.fromValue(value); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java new file mode 100644 index 000000000000..53bb7ac97c52 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java @@ -0,0 +1,333 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * An object to test discriminator of enum string + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class EnumStringDiscriminator { + /** + * enum string type + */ + @JsonAdapter(EnumStrTypeEnum.Adapter.class) + public enum EnumStrTypeEnum { + A("type_a"), + + B("type_b"); + + private String value; + + EnumStrTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStrTypeEnum fromValue(String value) { + for (EnumStrTypeEnum b : EnumStrTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumStrTypeEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumStrTypeEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumStrTypeEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStrTypeEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_ENUM_STR_TYPE = "enum_str_type"; + @SerializedName(SERIALIZED_NAME_ENUM_STR_TYPE) + @javax.annotation.Nonnull + protected EnumStrTypeEnum enumStrType; + + public EnumStringDiscriminator() { + + } + + public EnumStringDiscriminator enumStrType(@javax.annotation.Nonnull EnumStrTypeEnum enumStrType) { + this.enumStrType = enumStrType; + return this; + } + + /** + * enum string type + * @return enumStrType + */ + @javax.annotation.Nonnull + + public EnumStrTypeEnum getEnumStrType() { + return enumStrType; + } + + public void setEnumStrType(@javax.annotation.Nonnull EnumStrTypeEnum enumStrType) { + this.enumStrType = enumStrType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the EnumStringDiscriminator instance itself + */ + public EnumStringDiscriminator putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumStringDiscriminator enumStringDiscriminator = (EnumStringDiscriminator) o; + return Objects.equals(this.enumStrType, enumStringDiscriminator.enumStrType)&& + Objects.equals(this.additionalProperties, enumStringDiscriminator.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(enumStrType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumStringDiscriminator {\n"); + sb.append(" enumStrType: ").append(toIndentedString(enumStrType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("enum_str_type")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("enum_str_type")); + } + + /** + * 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 EnumStringDiscriminator + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!EnumStringDiscriminator.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in EnumStringDiscriminator is not found in the empty JSON string", EnumStringDiscriminator.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : EnumStringDiscriminator.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EnumStringDiscriminator.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EnumStringDiscriminator' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EnumStringDiscriminator.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EnumStringDiscriminator value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public EnumStringDiscriminator read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + EnumStringDiscriminator instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of EnumStringDiscriminator given an JSON string + * + * @param jsonString JSON string + * @return An instance of EnumStringDiscriminator + * @throws IOException if the JSON string is invalid with respect to EnumStringDiscriminator + */ + public static EnumStringDiscriminator fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, EnumStringDiscriminator.class); + } + + /** + * Convert an instance of EnumStringDiscriminator to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumTest.java new file mode 100644 index 000000000000..5150dce60f9f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EnumTest.java @@ -0,0 +1,806 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * EnumTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class EnumTest { + /** + * Gets or Sets enumString + */ + @JsonAdapter(EnumStringEnum.Adapter.class) + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringEnum fromValue(String value) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumStringEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumStringEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumStringEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_ENUM_STRING = "enum_string"; + @SerializedName(SERIALIZED_NAME_ENUM_STRING) + @javax.annotation.Nullable + private EnumStringEnum enumString; + + /** + * Gets or Sets enumStringRequired + */ + @JsonAdapter(EnumStringRequiredEnum.Adapter.class) + public enum EnumStringRequiredEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringRequiredEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringRequiredEnum fromValue(String value) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumStringRequiredEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumStringRequiredEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumStringRequiredEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringRequiredEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_ENUM_STRING_REQUIRED = "enum_string_required"; + @SerializedName(SERIALIZED_NAME_ENUM_STRING_REQUIRED) + @javax.annotation.Nonnull + private EnumStringRequiredEnum enumStringRequired; + + /** + * Gets or Sets enumInteger + */ + @JsonAdapter(EnumIntegerEnum.Adapter.class) + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumIntegerEnum fromValue(Integer value) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumIntegerEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumIntegerEnum read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return EnumIntegerEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + EnumIntegerEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_ENUM_INTEGER = "enum_integer"; + @SerializedName(SERIALIZED_NAME_ENUM_INTEGER) + @javax.annotation.Nullable + private EnumIntegerEnum enumInteger; + + /** + * Gets or Sets enumIntegerOnly + */ + @JsonAdapter(EnumIntegerOnlyEnum.Adapter.class) + public enum EnumIntegerOnlyEnum { + NUMBER_2(2), + + NUMBER_MINUS_2(-2); + + private Integer value; + + EnumIntegerOnlyEnum(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumIntegerOnlyEnum fromValue(Integer value) { + for (EnumIntegerOnlyEnum b : EnumIntegerOnlyEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumIntegerOnlyEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumIntegerOnlyEnum read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return EnumIntegerOnlyEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + EnumIntegerOnlyEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_ENUM_INTEGER_ONLY = "enum_integer_only"; + @SerializedName(SERIALIZED_NAME_ENUM_INTEGER_ONLY) + @javax.annotation.Nullable + private EnumIntegerOnlyEnum enumIntegerOnly; + + /** + * Gets or Sets enumNumber + */ + @JsonAdapter(EnumNumberEnum.Adapter.class) + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + public Double getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumNumberEnum fromValue(Double value) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumNumberEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumNumberEnum read(final JsonReader jsonReader) throws IOException { + Double value = jsonReader.nextDouble(); + return EnumNumberEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Double value = jsonElement.getAsDouble(); + EnumNumberEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_ENUM_NUMBER = "enum_number"; + @SerializedName(SERIALIZED_NAME_ENUM_NUMBER) + @javax.annotation.Nullable + private EnumNumberEnum enumNumber; + + public static final String SERIALIZED_NAME_OUTER_ENUM = "outerEnum"; + @SerializedName(SERIALIZED_NAME_OUTER_ENUM) + @javax.annotation.Nullable + private OuterEnum outerEnum; + + public static final String SERIALIZED_NAME_OUTER_ENUM_INTEGER = "outerEnumInteger"; + @Deprecated + @SerializedName(SERIALIZED_NAME_OUTER_ENUM_INTEGER) + @javax.annotation.Nullable + private OuterEnumInteger outerEnumInteger; + + public static final String SERIALIZED_NAME_OUTER_ENUM_DEFAULT_VALUE = "outerEnumDefaultValue"; + @SerializedName(SERIALIZED_NAME_OUTER_ENUM_DEFAULT_VALUE) + @javax.annotation.Nullable + private OuterEnumDefaultValue outerEnumDefaultValue = OuterEnumDefaultValue.PLACED; + + public static final String SERIALIZED_NAME_OUTER_ENUM_INTEGER_DEFAULT_VALUE = "outerEnumIntegerDefaultValue"; + @SerializedName(SERIALIZED_NAME_OUTER_ENUM_INTEGER_DEFAULT_VALUE) + @javax.annotation.Nullable + private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; + + public EnumTest() { + } + + public EnumTest enumString(@javax.annotation.Nullable EnumStringEnum enumString) { + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + */ + @javax.annotation.Nullable + + public EnumStringEnum getEnumString() { + return enumString; + } + + public void setEnumString(@javax.annotation.Nullable EnumStringEnum enumString) { + this.enumString = enumString; + } + + + public EnumTest enumStringRequired(@javax.annotation.Nonnull EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + */ + @javax.annotation.Nonnull + + public EnumStringRequiredEnum getEnumStringRequired() { + return enumStringRequired; + } + + public void setEnumStringRequired(@javax.annotation.Nonnull EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + + public EnumTest enumInteger(@javax.annotation.Nullable EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + */ + @javax.annotation.Nullable + + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + public void setEnumInteger(@javax.annotation.Nullable EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + + public EnumTest enumIntegerOnly(@javax.annotation.Nullable EnumIntegerOnlyEnum enumIntegerOnly) { + this.enumIntegerOnly = enumIntegerOnly; + return this; + } + + /** + * Get enumIntegerOnly + * @return enumIntegerOnly + */ + @javax.annotation.Nullable + + public EnumIntegerOnlyEnum getEnumIntegerOnly() { + return enumIntegerOnly; + } + + public void setEnumIntegerOnly(@javax.annotation.Nullable EnumIntegerOnlyEnum enumIntegerOnly) { + this.enumIntegerOnly = enumIntegerOnly; + } + + + public EnumTest enumNumber(@javax.annotation.Nullable EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + */ + @javax.annotation.Nullable + + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + public void setEnumNumber(@javax.annotation.Nullable EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + public EnumTest outerEnum(@javax.annotation.Nullable OuterEnum outerEnum) { + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + */ + @javax.annotation.Nullable + + public OuterEnum getOuterEnum() { + return outerEnum; + } + + public void setOuterEnum(@javax.annotation.Nullable OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + @Deprecated + public EnumTest outerEnumInteger(@javax.annotation.Nullable OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + return this; + } + + /** + * Get outerEnumInteger + * @return outerEnumInteger + * @deprecated + */ + @Deprecated + @javax.annotation.Nullable + + public OuterEnumInteger getOuterEnumInteger() { + return outerEnumInteger; + } + + @Deprecated + public void setOuterEnumInteger(@javax.annotation.Nullable OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + } + + + public EnumTest outerEnumDefaultValue(@javax.annotation.Nullable OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + return this; + } + + /** + * Get outerEnumDefaultValue + * @return outerEnumDefaultValue + */ + @javax.annotation.Nullable + + public OuterEnumDefaultValue getOuterEnumDefaultValue() { + return outerEnumDefaultValue; + } + + public void setOuterEnumDefaultValue(@javax.annotation.Nullable OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + } + + + public EnumTest outerEnumIntegerDefaultValue(@javax.annotation.Nullable OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + return this; + } + + /** + * Get outerEnumIntegerDefaultValue + * @return outerEnumIntegerDefaultValue + */ + @javax.annotation.Nullable + + public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { + return outerEnumIntegerDefaultValue; + } + + public void setOuterEnumIntegerDefaultValue(@javax.annotation.Nullable OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the EnumTest instance itself + */ + public EnumTest putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumIntegerOnly, enumTest.enumIntegerOnly) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum) && + Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && + Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && + Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue)&& + Objects.equals(this.additionalProperties, enumTest.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumStringRequired, enumInteger, enumIntegerOnly, enumNumber, outerEnum, outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumIntegerOnly: ").append(toIndentedString(enumIntegerOnly)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append(" outerEnumInteger: ").append(toIndentedString(outerEnumInteger)).append("\n"); + sb.append(" outerEnumDefaultValue: ").append(toIndentedString(outerEnumDefaultValue)).append("\n"); + sb.append(" outerEnumIntegerDefaultValue: ").append(toIndentedString(outerEnumIntegerDefaultValue)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("enum_string", "enum_string_required", "enum_integer", "enum_integer_only", "enum_number", "outerEnum", "outerEnumInteger", "outerEnumDefaultValue", "outerEnumIntegerDefaultValue")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("enum_string_required")); + } + + /** + * 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 EnumTest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!EnumTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in EnumTest is not found in the empty JSON string", EnumTest.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : EnumTest.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString())); + } + // validate the optional field `enum_string` + if (jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) { + EnumStringEnum.validateJsonElement(jsonObj.get("enum_string")); + } + if (!jsonObj.get("enum_string_required").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `enum_string_required` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string_required").toString())); + } + // validate the required field `enum_string_required` + EnumStringRequiredEnum.validateJsonElement(jsonObj.get("enum_string_required")); + // validate the optional field `enum_integer` + if (jsonObj.get("enum_integer") != null && !jsonObj.get("enum_integer").isJsonNull()) { + EnumIntegerEnum.validateJsonElement(jsonObj.get("enum_integer")); + } + // validate the optional field `enum_integer_only` + if (jsonObj.get("enum_integer_only") != null && !jsonObj.get("enum_integer_only").isJsonNull()) { + EnumIntegerOnlyEnum.validateJsonElement(jsonObj.get("enum_integer_only")); + } + // validate the optional field `enum_number` + if (jsonObj.get("enum_number") != null && !jsonObj.get("enum_number").isJsonNull()) { + EnumNumberEnum.validateJsonElement(jsonObj.get("enum_number")); + } + // validate the optional field `outerEnum` + if (jsonObj.get("outerEnum") != null && !jsonObj.get("outerEnum").isJsonNull()) { + OuterEnum.validateJsonElement(jsonObj.get("outerEnum")); + } + // validate the optional field `outerEnumInteger` + if (jsonObj.get("outerEnumInteger") != null && !jsonObj.get("outerEnumInteger").isJsonNull()) { + OuterEnumInteger.validateJsonElement(jsonObj.get("outerEnumInteger")); + } + // validate the optional field `outerEnumDefaultValue` + if (jsonObj.get("outerEnumDefaultValue") != null && !jsonObj.get("outerEnumDefaultValue").isJsonNull()) { + OuterEnumDefaultValue.validateJsonElement(jsonObj.get("outerEnumDefaultValue")); + } + // validate the optional field `outerEnumIntegerDefaultValue` + if (jsonObj.get("outerEnumIntegerDefaultValue") != null && !jsonObj.get("outerEnumIntegerDefaultValue").isJsonNull()) { + OuterEnumIntegerDefaultValue.validateJsonElement(jsonObj.get("outerEnumIntegerDefaultValue")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EnumTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EnumTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EnumTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EnumTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public EnumTest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + EnumTest instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of EnumTest given an JSON string + * + * @param jsonString JSON string + * @return An instance of EnumTest + * @throws IOException if the JSON string is invalid with respect to EnumTest + */ + public static EnumTest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, EnumTest.class); + } + + /** + * Convert an instance of EnumTest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EquilateralTriangle.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EquilateralTriangle.java new file mode 100644 index 000000000000..976b2f131c19 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/EquilateralTriangle.java @@ -0,0 +1,313 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * EquilateralTriangle + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class EquilateralTriangle { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + @javax.annotation.Nonnull + private String shapeType; + + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + @javax.annotation.Nonnull + private String triangleType; + + public EquilateralTriangle() { + } + + public EquilateralTriangle shapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + */ + @javax.annotation.Nonnull + + public String getShapeType() { + return shapeType; + } + + public void setShapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + } + + + public EquilateralTriangle triangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + */ + @javax.annotation.Nonnull + + public String getTriangleType() { + return triangleType; + } + + public void setTriangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the EquilateralTriangle instance itself + */ + public EquilateralTriangle putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EquilateralTriangle equilateralTriangle = (EquilateralTriangle) o; + return Objects.equals(this.shapeType, equilateralTriangle.shapeType) && + Objects.equals(this.triangleType, equilateralTriangle.triangleType)&& + Objects.equals(this.additionalProperties, equilateralTriangle.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, triangleType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EquilateralTriangle {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("shapeType", "triangleType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("shapeType", "triangleType")); + } + + /** + * 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 EquilateralTriangle + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!EquilateralTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in EquilateralTriangle is not found in the empty JSON string", EquilateralTriangle.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : EquilateralTriangle.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("shapeType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); + } + if (!jsonObj.get("triangleType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EquilateralTriangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EquilateralTriangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EquilateralTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EquilateralTriangle value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public EquilateralTriangle read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + EquilateralTriangle instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of EquilateralTriangle given an JSON string + * + * @param jsonString JSON string + * @return An instance of EquilateralTriangle + * @throws IOException if the JSON string is invalid with respect to EquilateralTriangle + */ + public static EquilateralTriangle fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, EquilateralTriangle.class); + } + + /** + * Convert an instance of EquilateralTriangle to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeAnyOfWIthSameErasureGet200Response.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeAnyOfWIthSameErasureGet200Response.java new file mode 100644 index 000000000000..70aa2bbd7821 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeAnyOfWIthSameErasureGet200Response.java @@ -0,0 +1,348 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FakeAnyOfWIthSameErasureGet200Response extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(FakeAnyOfWIthSameErasureGet200Response.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FakeAnyOfWIthSameErasureGet200Response instance itself + */ + public FakeAnyOfWIthSameErasureGet200Response putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(FakeAnyOfWIthSameErasureGet200Response instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched anyOf schema. + */ + private static void writeUnconsumedProperties(FakeAnyOfWIthSameErasureGet200Response value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 FakeAnyOfWIthSameErasureGet200Response + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + } + + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for FakeAnyOfWIthSameErasureGet200Response: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FakeAnyOfWIthSameErasureGet200Response.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FakeAnyOfWIthSameErasureGet200Response' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final Type typeInstanceListString = new TypeToken>(){}.getType(); + final TypeAdapter> adapterListString = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceListString)); + final Type typeInstanceListInteger = new TypeToken>(){}.getType(); + final TypeAdapter> adapterListInteger = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceListInteger)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FakeAnyOfWIthSameErasureGet200Response value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `List` + if (value.getActualInstance() instanceof List) { + element = adapterListString.toJsonTree((List)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: List, List"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public FakeAnyOfWIthSameErasureGet200Response read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + FakeAnyOfWIthSameErasureGet200Response ret = new FakeAnyOfWIthSameErasureGet200Response(); + ret.setActualInstance(adapterListString.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'List'", e); + } + + + throw new IOException(String.format("Failed deserialization for FakeAnyOfWIthSameErasureGet200Response: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public FakeAnyOfWIthSameErasureGet200Response() { + super("anyOf", Boolean.FALSE); + } + + public FakeAnyOfWIthSameErasureGet200Response(List o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + + static { + schemas.put("List", List.class); + schemas.put("List", List.class); + } + + @Override + public Map> getSchemas() { + return FakeAnyOfWIthSameErasureGet200Response.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * List, List + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(List.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be List, List"); + } + + /** + * Get the actual instance, which can be the following: + * List, List + * + * @return The actual instance (List, List) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `List`. If the actual instance is not `List`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `List` + * @throws ClassCastException if the instance is not `List` + */ + @SuppressWarnings("unchecked") + public List getListString() throws ClassCastException { + return (List)super.getActualInstance(); + } + + /** + * Get the actual instance of `List`. If the actual instance is not `List`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `List` + * @throws ClassCastException if the instance is not `List` + */ + @SuppressWarnings("unchecked") + public List getListInteger() throws ClassCastException { + return (List)super.getActualInstance(); + } + + + + /** + * Create an instance of FakeAnyOfWIthSameErasureGet200Response given an JSON string + * + * @param jsonString JSON string + * @return An instance of FakeAnyOfWIthSameErasureGet200Response + * @throws IOException if the JSON string is invalid with respect to FakeAnyOfWIthSameErasureGet200Response + */ + public static FakeAnyOfWIthSameErasureGet200Response fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FakeAnyOfWIthSameErasureGet200Response.class); + } + + /** + * Convert an instance of FakeAnyOfWIthSameErasureGet200Response to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeOneOfWIthSameErasureGet200Response.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeOneOfWIthSameErasureGet200Response.java new file mode 100644 index 000000000000..93901111d908 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeOneOfWIthSameErasureGet200Response.java @@ -0,0 +1,354 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FakeOneOfWIthSameErasureGet200Response extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(FakeOneOfWIthSameErasureGet200Response.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FakeOneOfWIthSameErasureGet200Response instance itself + */ + public FakeOneOfWIthSameErasureGet200Response putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(FakeOneOfWIthSameErasureGet200Response instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(FakeOneOfWIthSameErasureGet200Response value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 FakeOneOfWIthSameErasureGet200Response + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for FakeOneOfWIthSameErasureGet200Response: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FakeOneOfWIthSameErasureGet200Response.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FakeOneOfWIthSameErasureGet200Response' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final Type typeInstanceListString = new TypeToken>(){}.getType(); + final TypeAdapter> adapterListString = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceListString)); + final Type typeInstanceListInteger = new TypeToken>(){}.getType(); + final TypeAdapter> adapterListInteger = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceListInteger)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FakeOneOfWIthSameErasureGet200Response value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `List` + if (value.getActualInstance() instanceof List) { + element = adapterListString.toJsonTree((List)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: List, List"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public FakeOneOfWIthSameErasureGet200Response read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + if (!element.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type String in the JSON string but got `%s`", element.toString())); + } + } + actualAdapter = adapterListString; + match++; + log.log(Level.FINER, "Input data matches schema 'List'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'List'", e); + } + + if (match == 1) { + FakeOneOfWIthSameErasureGet200Response ret = new FakeOneOfWIthSameErasureGet200Response(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for FakeOneOfWIthSameErasureGet200Response: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public FakeOneOfWIthSameErasureGet200Response() { + super("oneOf", Boolean.FALSE); + } + + public FakeOneOfWIthSameErasureGet200Response(List o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + + static { + schemas.put("List", List.class); + schemas.put("List", List.class); + } + + @Override + public Map> getSchemas() { + return FakeOneOfWIthSameErasureGet200Response.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * List, List + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(List.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be List, List"); + } + + /** + * Get the actual instance, which can be the following: + * List, List + * + * @return The actual instance (List, List) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `List`. If the actual instance is not `List`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `List` + * @throws ClassCastException if the instance is not `List` + */ + @SuppressWarnings("unchecked") + public List getListString() throws ClassCastException { + return (List)super.getActualInstance(); + } + + /** + * Get the actual instance of `List`. If the actual instance is not `List`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `List` + * @throws ClassCastException if the instance is not `List` + */ + @SuppressWarnings("unchecked") + public List getListInteger() throws ClassCastException { + return (List)super.getActualInstance(); + } + + + + /** + * Create an instance of FakeOneOfWIthSameErasureGet200Response given an JSON string + * + * @param jsonString JSON string + * @return An instance of FakeOneOfWIthSameErasureGet200Response + * @throws IOException if the JSON string is invalid with respect to FakeOneOfWIthSameErasureGet200Response + */ + public static FakeOneOfWIthSameErasureGet200Response fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FakeOneOfWIthSameErasureGet200Response.class); + } + + /** + * Convert an instance of FakeOneOfWIthSameErasureGet200Response to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeRefParameterPetIdParameter.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeRefParameterPetIdParameter.java new file mode 100644 index 000000000000..04286763606a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FakeRefParameterPetIdParameter.java @@ -0,0 +1,382 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FakeRefParameterPetIdParameter extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(FakeRefParameterPetIdParameter.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FakeRefParameterPetIdParameter instance itself + */ + public FakeRefParameterPetIdParameter putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(FakeRefParameterPetIdParameter instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(FakeRefParameterPetIdParameter value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 FakeRefParameterPetIdParameter + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + } + + // deserialize Integer + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for FakeRefParameterPetIdParameter: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FakeRefParameterPetIdParameter.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FakeRefParameterPetIdParameter' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + final TypeAdapter adapterInteger = gson.getDelegateAdapter(this, TypeToken.get(Integer.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FakeRefParameterPetIdParameter value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `String` + if (value.getActualInstance() instanceof String) { + element = adapterString.toJsonTree((String)value.getActualInstance()); + } + // check if the actual instance is of the type `Integer` + if (value.getActualInstance() instanceof Integer) { + element = adapterInteger.toJsonTree((Integer)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Integer, String"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public FakeRefParameterPetIdParameter read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + // deserialize Integer + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterInteger; + match++; + log.log(Level.FINER, "Input data matches schema 'Integer'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Integer failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Integer'", e); + } + + if (match == 1) { + FakeRefParameterPetIdParameter ret = new FakeRefParameterPetIdParameter(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for FakeRefParameterPetIdParameter: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public FakeRefParameterPetIdParameter() { + super("oneOf", Boolean.FALSE); + } + + public FakeRefParameterPetIdParameter(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public FakeRefParameterPetIdParameter(Integer o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("String", String.class); + schemas.put("Integer", Integer.class); + } + + @Override + public Map> getSchemas() { + return FakeRefParameterPetIdParameter.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Integer, String + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(String.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Integer.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Integer, String"); + } + + /** + * Get the actual instance, which can be the following: + * Integer, String + * + * @return The actual instance (Integer, String) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + @SuppressWarnings("unchecked") + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + /** + * Get the actual instance of `Integer`. If the actual instance is not `Integer`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Integer` + * @throws ClassCastException if the instance is not `Integer` + */ + @SuppressWarnings("unchecked") + public Integer getInteger() throws ClassCastException { + return (Integer)super.getActualInstance(); + } + + + + /** + * Create an instance of FakeRefParameterPetIdParameter given an JSON string + * + * @param jsonString JSON string + * @return An instance of FakeRefParameterPetIdParameter + * @throws IOException if the JSON string is invalid with respect to FakeRefParameterPetIdParameter + */ + public static FakeRefParameterPetIdParameter fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FakeRefParameterPetIdParameter.class); + } + + /** + * Convert an instance of FakeRefParameterPetIdParameter to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java new file mode 100644 index 000000000000..7801dedc6c54 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -0,0 +1,327 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * FileSchemaTestClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FileSchemaTestClass { + public static final String SERIALIZED_NAME_FILE = "file"; + @SerializedName(SERIALIZED_NAME_FILE) + @javax.annotation.Nullable + private ModelFile _file; + + public static final String SERIALIZED_NAME_FILES = "files"; + @SerializedName(SERIALIZED_NAME_FILES) + @javax.annotation.Nullable + private List files = new ArrayList<>(); + + public FileSchemaTestClass() { + } + + public FileSchemaTestClass _file(@javax.annotation.Nullable ModelFile _file) { + this._file = _file; + return this; + } + + /** + * Get _file + * @return _file + */ + @javax.annotation.Nullable + + public ModelFile getFile() { + return _file; + } + + public void setFile(@javax.annotation.Nullable ModelFile _file) { + this._file = _file; + } + + + public FileSchemaTestClass files(@javax.annotation.Nullable List files) { + this.files = files; + return this; + } + + public FileSchemaTestClass addFilesItem(ModelFile filesItem) { + if (this.files == null) { + this.files = new ArrayList<>(); + } + this.files.add(filesItem); + return this; + } + + /** + * Get files + * @return files + */ + @javax.annotation.Nullable + + public List getFiles() { + return files; + } + + public void setFiles(@javax.annotation.Nullable List files) { + this.files = files; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FileSchemaTestClass instance itself + */ + public FileSchemaTestClass putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; + return Objects.equals(this._file, fileSchemaTestClass._file) && + Objects.equals(this.files, fileSchemaTestClass.files)&& + Objects.equals(this.additionalProperties, fileSchemaTestClass.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(_file, files, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + sb.append(" _file: ").append(toIndentedString(_file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("file", "files")); + + // 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 FileSchemaTestClass + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!FileSchemaTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in FileSchemaTestClass is not found in the empty JSON string", FileSchemaTestClass.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `file` + if (jsonObj.get("file") != null && !jsonObj.get("file").isJsonNull()) { + ModelFile.validateJsonElement(jsonObj.get("file")); + } + if (jsonObj.get("files") != null && !jsonObj.get("files").isJsonNull()) { + com.google.gson.JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files"); + if (jsonArrayfiles != null) { + // ensure the json data is an array + if (!jsonObj.get("files").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `files` to be an array in the JSON string but got `%s`", jsonObj.get("files").toString())); + } + + // validate the optional field `files` (array) + for (int i = 0; i < jsonArrayfiles.size(); i++) { + ModelFile.validateJsonElement(jsonArrayfiles.get(i)); + }; + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FileSchemaTestClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FileSchemaTestClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(FileSchemaTestClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FileSchemaTestClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public FileSchemaTestClass read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + FileSchemaTestClass instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of FileSchemaTestClass given an JSON string + * + * @param jsonString JSON string + * @return An instance of FileSchemaTestClass + * @throws IOException if the JSON string is invalid with respect to FileSchemaTestClass + */ + public static FileSchemaTestClass fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FileSchemaTestClass.class); + } + + /** + * Convert an instance of FileSchemaTestClass to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Foo.java new file mode 100644 index 000000000000..4550390d937e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Foo.java @@ -0,0 +1,276 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Foo + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Foo { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + @javax.annotation.Nullable + private String bar = "bar"; + + public Foo() { + } + + public Foo bar(@javax.annotation.Nullable String bar) { + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + */ + @javax.annotation.Nullable + + public String getBar() { + return bar; + } + + public void setBar(@javax.annotation.Nullable String bar) { + this.bar = bar; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Foo instance itself + */ + public Foo putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Foo foo = (Foo) o; + return Objects.equals(this.bar, foo.bar)&& + Objects.equals(this.additionalProperties, foo.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(bar, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Foo {\n"); + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("bar")); + + // 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 Foo + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Foo.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Foo is not found in the empty JSON string", Foo.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Foo.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Foo' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Foo.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Foo value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Foo read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Foo instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Foo given an JSON string + * + * @param jsonString JSON string + * @return An instance of Foo + * @throws IOException if the JSON string is invalid with respect to Foo + */ + public static Foo fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Foo.class); + } + + /** + * Convert an instance of Foo to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java new file mode 100644 index 000000000000..63d7a6f3a168 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java @@ -0,0 +1,277 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * FooGetDefaultResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FooGetDefaultResponse { + public static final String SERIALIZED_NAME_STRING = "string"; + @SerializedName(SERIALIZED_NAME_STRING) + @javax.annotation.Nullable + private Foo string; + + public FooGetDefaultResponse() { + } + + public FooGetDefaultResponse string(@javax.annotation.Nullable Foo string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + */ + @javax.annotation.Nullable + + public Foo getString() { + return string; + } + + public void setString(@javax.annotation.Nullable Foo string) { + this.string = string; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FooGetDefaultResponse instance itself + */ + public FooGetDefaultResponse putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FooGetDefaultResponse fooGetDefaultResponse = (FooGetDefaultResponse) o; + return Objects.equals(this.string, fooGetDefaultResponse.string)&& + Objects.equals(this.additionalProperties, fooGetDefaultResponse.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(string, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FooGetDefaultResponse {\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("string")); + + // 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 FooGetDefaultResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!FooGetDefaultResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in FooGetDefaultResponse is not found in the empty JSON string", FooGetDefaultResponse.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `string` + if (jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) { + Foo.validateJsonElement(jsonObj.get("string")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FooGetDefaultResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FooGetDefaultResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(FooGetDefaultResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FooGetDefaultResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public FooGetDefaultResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + FooGetDefaultResponse instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of FooGetDefaultResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of FooGetDefaultResponse + * @throws IOException if the JSON string is invalid with respect to FooGetDefaultResponse + */ + public static FooGetDefaultResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FooGetDefaultResponse.class); + } + + /** + * Convert an instance of FooGetDefaultResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FormatTest.java new file mode 100644 index 000000000000..aeefd766877b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FormatTest.java @@ -0,0 +1,745 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * FormatTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FormatTest { + public static final String SERIALIZED_NAME_INTEGER = "integer"; + @SerializedName(SERIALIZED_NAME_INTEGER) + @javax.annotation.Nullable + private Integer integer; + + public static final String SERIALIZED_NAME_INT32 = "int32"; + @SerializedName(SERIALIZED_NAME_INT32) + @javax.annotation.Nullable + private Integer int32; + + public static final String SERIALIZED_NAME_INT64 = "int64"; + @SerializedName(SERIALIZED_NAME_INT64) + @javax.annotation.Nullable + private Long int64; + + public static final String SERIALIZED_NAME_NUMBER = "number"; + @SerializedName(SERIALIZED_NAME_NUMBER) + @javax.annotation.Nonnull + private BigDecimal number; + + public static final String SERIALIZED_NAME_FLOAT = "float"; + @SerializedName(SERIALIZED_NAME_FLOAT) + @javax.annotation.Nullable + private Float _float; + + public static final String SERIALIZED_NAME_DOUBLE = "double"; + @SerializedName(SERIALIZED_NAME_DOUBLE) + @javax.annotation.Nullable + private Double _double; + + public static final String SERIALIZED_NAME_DECIMAL = "decimal"; + @SerializedName(SERIALIZED_NAME_DECIMAL) + @javax.annotation.Nullable + private BigDecimal decimal; + + public static final String SERIALIZED_NAME_STRING = "string"; + @SerializedName(SERIALIZED_NAME_STRING) + @javax.annotation.Nullable + private String string; + + public static final String SERIALIZED_NAME_BYTE = "byte"; + @SerializedName(SERIALIZED_NAME_BYTE) + @javax.annotation.Nonnull + private byte[] _byte; + + public static final String SERIALIZED_NAME_BINARY = "binary"; + @SerializedName(SERIALIZED_NAME_BINARY) + @javax.annotation.Nullable + private File binary; + + public static final String SERIALIZED_NAME_DATE = "date"; + @SerializedName(SERIALIZED_NAME_DATE) + @javax.annotation.Nonnull + private LocalDate date; + + public static final String SERIALIZED_NAME_DATE_TIME = "dateTime"; + @SerializedName(SERIALIZED_NAME_DATE_TIME) + @javax.annotation.Nullable + private OffsetDateTime dateTime; + + public static final String SERIALIZED_NAME_UUID = "uuid"; + @SerializedName(SERIALIZED_NAME_UUID) + @javax.annotation.Nullable + private UUID uuid; + + public static final String SERIALIZED_NAME_UUID_WITH_DEFAULT = "uuid_with_default"; + @SerializedName(SERIALIZED_NAME_UUID_WITH_DEFAULT) + @javax.annotation.Nullable + private UUID uuidWithDefault = UUID.fromString("11111111-206d-4f12-9f12-3d1e525a8e84"); + + public static final String SERIALIZED_NAME_PASSWORD = "password"; + @SerializedName(SERIALIZED_NAME_PASSWORD) + @javax.annotation.Nonnull + private String password; + + public static final String SERIALIZED_NAME_PATTERN_WITH_DIGITS = "pattern_with_digits"; + @SerializedName(SERIALIZED_NAME_PATTERN_WITH_DIGITS) + @javax.annotation.Nullable + private String patternWithDigits; + + public static final String SERIALIZED_NAME_PATTERN_WITH_DIGITS_AND_DELIMITER = "pattern_with_digits_and_delimiter"; + @SerializedName(SERIALIZED_NAME_PATTERN_WITH_DIGITS_AND_DELIMITER) + @javax.annotation.Nullable + private String patternWithDigitsAndDelimiter; + + public FormatTest() { + } + + public FormatTest integer(@javax.annotation.Nullable Integer integer) { + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + */ + @javax.annotation.Nullable + + public Integer getInteger() { + return integer; + } + + public void setInteger(@javax.annotation.Nullable Integer integer) { + this.integer = integer; + } + + + public FormatTest int32(@javax.annotation.Nullable Integer int32) { + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + */ + @javax.annotation.Nullable + + public Integer getInt32() { + return int32; + } + + public void setInt32(@javax.annotation.Nullable Integer int32) { + this.int32 = int32; + } + + + public FormatTest int64(@javax.annotation.Nullable Long int64) { + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + */ + @javax.annotation.Nullable + + public Long getInt64() { + return int64; + } + + public void setInt64(@javax.annotation.Nullable Long int64) { + this.int64 = int64; + } + + + public FormatTest number(@javax.annotation.Nonnull BigDecimal number) { + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + */ + @javax.annotation.Nonnull + + public BigDecimal getNumber() { + return number; + } + + public void setNumber(@javax.annotation.Nonnull BigDecimal number) { + this.number = number; + } + + + public FormatTest _float(@javax.annotation.Nullable Float _float) { + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + */ + @javax.annotation.Nullable + + public Float getFloat() { + return _float; + } + + public void setFloat(@javax.annotation.Nullable Float _float) { + this._float = _float; + } + + + public FormatTest _double(@javax.annotation.Nullable Double _double) { + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + */ + @javax.annotation.Nullable + + public Double getDouble() { + return _double; + } + + public void setDouble(@javax.annotation.Nullable Double _double) { + this._double = _double; + } + + + public FormatTest decimal(@javax.annotation.Nullable BigDecimal decimal) { + this.decimal = decimal; + return this; + } + + /** + * Get decimal + * @return decimal + */ + @javax.annotation.Nullable + + public BigDecimal getDecimal() { + return decimal; + } + + public void setDecimal(@javax.annotation.Nullable BigDecimal decimal) { + this.decimal = decimal; + } + + + public FormatTest string(@javax.annotation.Nullable String string) { + this.string = string; + return this; + } + + /** + * Get string + * @return string + */ + @javax.annotation.Nullable + + public String getString() { + return string; + } + + public void setString(@javax.annotation.Nullable String string) { + this.string = string; + } + + + public FormatTest _byte(@javax.annotation.Nonnull byte[] _byte) { + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + */ + @javax.annotation.Nonnull + + public byte[] getByte() { + return _byte; + } + + public void setByte(@javax.annotation.Nonnull byte[] _byte) { + this._byte = _byte; + } + + + public FormatTest binary(@javax.annotation.Nullable File binary) { + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + */ + @javax.annotation.Nullable + + public File getBinary() { + return binary; + } + + public void setBinary(@javax.annotation.Nullable File binary) { + this.binary = binary; + } + + + public FormatTest date(@javax.annotation.Nonnull LocalDate date) { + this.date = date; + return this; + } + + /** + * Get date + * @return date + */ + @javax.annotation.Nonnull + + public LocalDate getDate() { + return date; + } + + public void setDate(@javax.annotation.Nonnull LocalDate date) { + this.date = date; + } + + + public FormatTest dateTime(@javax.annotation.Nullable OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + */ + @javax.annotation.Nullable + + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(@javax.annotation.Nullable OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + + public FormatTest uuid(@javax.annotation.Nullable UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + */ + @javax.annotation.Nullable + + public UUID getUuid() { + return uuid; + } + + public void setUuid(@javax.annotation.Nullable UUID uuid) { + this.uuid = uuid; + } + + + public FormatTest uuidWithDefault(@javax.annotation.Nullable UUID uuidWithDefault) { + this.uuidWithDefault = uuidWithDefault; + return this; + } + + /** + * Get uuidWithDefault + * @return uuidWithDefault + */ + @javax.annotation.Nullable + + public UUID getUuidWithDefault() { + return uuidWithDefault; + } + + public void setUuidWithDefault(@javax.annotation.Nullable UUID uuidWithDefault) { + this.uuidWithDefault = uuidWithDefault; + } + + + public FormatTest password(@javax.annotation.Nonnull String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + */ + @javax.annotation.Nonnull + + public String getPassword() { + return password; + } + + public void setPassword(@javax.annotation.Nonnull String password) { + this.password = password; + } + + + public FormatTest patternWithDigits(@javax.annotation.Nullable String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + return this; + } + + /** + * A string that is a 10 digit number. Can have leading zeros. + * @return patternWithDigits + */ + @javax.annotation.Nullable + + public String getPatternWithDigits() { + return patternWithDigits; + } + + public void setPatternWithDigits(@javax.annotation.Nullable String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + } + + + public FormatTest patternWithDigitsAndDelimiter(@javax.annotation.Nullable String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + return this; + } + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + * @return patternWithDigitsAndDelimiter + */ + @javax.annotation.Nullable + + public String getPatternWithDigitsAndDelimiter() { + return patternWithDigitsAndDelimiter; + } + + public void setPatternWithDigitsAndDelimiter(@javax.annotation.Nullable String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FormatTest instance itself + */ + public FormatTest putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.decimal, formatTest.decimal) && + Objects.equals(this.string, formatTest.string) && + Arrays.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.uuidWithDefault, formatTest.uuidWithDefault) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.patternWithDigits, formatTest.patternWithDigits) && + Objects.equals(this.patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter)&& + Objects.equals(this.additionalProperties, formatTest.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, decimal, string, Arrays.hashCode(_byte), binary, date, dateTime, uuid, uuidWithDefault, password, patternWithDigits, patternWithDigitsAndDelimiter, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" decimal: ").append(toIndentedString(decimal)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" uuidWithDefault: ").append(toIndentedString(uuidWithDefault)).append("\n"); + sb.append(" password: ").append("*").append("\n"); + sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); + sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("integer", "int32", "int64", "number", "float", "double", "decimal", "string", "byte", "binary", "date", "dateTime", "uuid", "uuid_with_default", "password", "pattern_with_digits", "pattern_with_digits_and_delimiter")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("number", "byte", "date", "password")); + } + + /** + * 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 FormatTest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!FormatTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in FormatTest is not found in the empty JSON string", FormatTest.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : FormatTest.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) && !jsonObj.get("string").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string").toString())); + } + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); + } + if ((jsonObj.get("uuid_with_default") != null && !jsonObj.get("uuid_with_default").isJsonNull()) && !jsonObj.get("uuid_with_default").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `uuid_with_default` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid_with_default").toString())); + } + if (!jsonObj.get("password").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); + } + if ((jsonObj.get("pattern_with_digits") != null && !jsonObj.get("pattern_with_digits").isJsonNull()) && !jsonObj.get("pattern_with_digits").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `pattern_with_digits` to be a primitive type in the JSON string but got `%s`", jsonObj.get("pattern_with_digits").toString())); + } + if ((jsonObj.get("pattern_with_digits_and_delimiter") != null && !jsonObj.get("pattern_with_digits_and_delimiter").isJsonNull()) && !jsonObj.get("pattern_with_digits_and_delimiter").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `pattern_with_digits_and_delimiter` to be a primitive type in the JSON string but got `%s`", jsonObj.get("pattern_with_digits_and_delimiter").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FormatTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FormatTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(FormatTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FormatTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public FormatTest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + FormatTest instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of FormatTest given an JSON string + * + * @param jsonString JSON string + * @return An instance of FormatTest + * @throws IOException if the JSON string is invalid with respect to FormatTest + */ + public static FormatTest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FormatTest.class); + } + + /** + * Convert an instance of FormatTest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java new file mode 100644 index 000000000000..ddafa63f6b53 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java @@ -0,0 +1,307 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * FreeFormObjectTestClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FreeFormObjectTestClass { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nullable + private String name; + + public static final String SERIALIZED_NAME_PROPERTIES = "properties"; + @SerializedName(SERIALIZED_NAME_PROPERTIES) + @javax.annotation.Nullable + private FreeFormObjectTestClassProperties properties; + + public FreeFormObjectTestClass() { + } + + public FreeFormObjectTestClass name(@javax.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nullable + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nullable String name) { + this.name = name; + } + + + public FreeFormObjectTestClass properties(@javax.annotation.Nullable FreeFormObjectTestClassProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get properties + * @return properties + */ + @javax.annotation.Nullable + + public FreeFormObjectTestClassProperties getProperties() { + return properties; + } + + public void setProperties(@javax.annotation.Nullable FreeFormObjectTestClassProperties properties) { + this.properties = properties; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FreeFormObjectTestClass instance itself + */ + public FreeFormObjectTestClass putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FreeFormObjectTestClass freeFormObjectTestClass = (FreeFormObjectTestClass) o; + return Objects.equals(this.name, freeFormObjectTestClass.name) && + Objects.equals(this.properties, freeFormObjectTestClass.properties)&& + Objects.equals(this.additionalProperties, freeFormObjectTestClass.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(name, properties, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FreeFormObjectTestClass {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("name", "properties")); + + // 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 FreeFormObjectTestClass + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!FreeFormObjectTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in FreeFormObjectTestClass is not found in the empty JSON string", FreeFormObjectTestClass.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // validate the optional field `properties` + if (jsonObj.get("properties") != null && !jsonObj.get("properties").isJsonNull()) { + FreeFormObjectTestClassProperties.validateJsonElement(jsonObj.get("properties")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FreeFormObjectTestClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FreeFormObjectTestClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(FreeFormObjectTestClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FreeFormObjectTestClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public FreeFormObjectTestClass read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + FreeFormObjectTestClass instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of FreeFormObjectTestClass given an JSON string + * + * @param jsonString JSON string + * @return An instance of FreeFormObjectTestClass + * @throws IOException if the JSON string is invalid with respect to FreeFormObjectTestClass + */ + public static FreeFormObjectTestClass fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FreeFormObjectTestClass.class); + } + + /** + * Convert an instance of FreeFormObjectTestClass to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java new file mode 100644 index 000000000000..eb8dc50eff6d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java @@ -0,0 +1,383 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FreeFormObjectTestClassProperties extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(FreeFormObjectTestClassProperties.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FreeFormObjectTestClassProperties instance itself + */ + public FreeFormObjectTestClassProperties putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(FreeFormObjectTestClassProperties instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(FreeFormObjectTestClassProperties value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 FreeFormObjectTestClassProperties + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + } + + // deserialize Map + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Map failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for FreeFormObjectTestClassProperties: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FreeFormObjectTestClassProperties.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FreeFormObjectTestClassProperties' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + final Type typeInstanceMapStringObject = new TypeToken>(){}.getType(); + final TypeAdapter> adapterMapStringObject = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceMapStringObject)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FreeFormObjectTestClassProperties value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `String` + if (value.getActualInstance() instanceof String) { + element = adapterString.toJsonTree((String)value.getActualInstance()); + } + // check if the actual instance is of the type `Map` + if (value.getActualInstance() instanceof Map) { + element = adapterMapStringObject.toJsonTree((Map)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Map, String"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public FreeFormObjectTestClassProperties read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + // deserialize Map + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterMapStringObject; + match++; + log.log(Level.FINER, "Input data matches schema 'Map'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Map failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Map'", e); + } + + if (match == 1) { + FreeFormObjectTestClassProperties ret = new FreeFormObjectTestClassProperties(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for FreeFormObjectTestClassProperties: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public FreeFormObjectTestClassProperties() { + super("oneOf", Boolean.FALSE); + } + + public FreeFormObjectTestClassProperties(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public FreeFormObjectTestClassProperties(Map o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("String", String.class); + schemas.put("Map", Map.class); + } + + @Override + public Map> getSchemas() { + return FreeFormObjectTestClassProperties.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Map, String + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(String.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Map.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Map, String"); + } + + /** + * Get the actual instance, which can be the following: + * Map, String + * + * @return The actual instance (Map, String) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + @SuppressWarnings("unchecked") + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + /** + * Get the actual instance of `Map`. If the actual instance is not `Map`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Map` + * @throws ClassCastException if the instance is not `Map` + */ + @SuppressWarnings("unchecked") + public Map getMapStringObject() throws ClassCastException { + return (Map)super.getActualInstance(); + } + + + + /** + * Create an instance of FreeFormObjectTestClassProperties given an JSON string + * + * @param jsonString JSON string + * @return An instance of FreeFormObjectTestClassProperties + * @throws IOException if the JSON string is invalid with respect to FreeFormObjectTestClassProperties + */ + public static FreeFormObjectTestClassProperties fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FreeFormObjectTestClassProperties.class); + } + + /** + * Convert an instance of FreeFormObjectTestClassProperties to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Fruit.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Fruit.java new file mode 100644 index 000000000000..5a7ab2df272b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Fruit.java @@ -0,0 +1,274 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Fruit extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Fruit.class.getName()); + + + /** + * 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 Fruit + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize Apple + try { + // validate the JSON object to see if any exception is thrown + Apple.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Apple failed with `%s`.", e.getMessage())); + } + + // deserialize Banana + try { + // validate the JSON object to see if any exception is thrown + Banana.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Banana failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Fruit: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Fruit.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Fruit' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterApple = gson.getDelegateAdapter(this, TypeToken.get(Apple.class)); + final TypeAdapter adapterBanana = gson.getDelegateAdapter(this, TypeToken.get(Banana.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Fruit value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Apple` + if (value.getActualInstance() instanceof Apple) { + element = adapterApple.toJsonTree((Apple)value.getActualInstance()); + } + // check if the actual instance is of the type `Banana` + if (value.getActualInstance() instanceof Banana) { + element = adapterBanana.toJsonTree((Banana)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Apple, Banana"); + } + + elementAdapter.write(out, element); + } + + @Override + public Fruit read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Apple + try { + // validate the JSON object to see if any exception is thrown + Apple.validateJsonElement(jsonElement); + actualAdapter = adapterApple; + match++; + log.log(Level.FINER, "Input data matches schema 'Apple'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Apple failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Apple'", e); + } + + // deserialize Banana + try { + // validate the JSON object to see if any exception is thrown + Banana.validateJsonElement(jsonElement); + actualAdapter = adapterBanana; + match++; + log.log(Level.FINER, "Input data matches schema 'Banana'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Banana failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Banana'", e); + } + + if (match == 1) { + Fruit ret = new Fruit(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Fruit: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Fruit() { + super("oneOf", Boolean.FALSE); + } + + public Fruit(Apple o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + public Fruit(Banana o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Apple", Apple.class); + schemas.put("Banana", Banana.class); + } + + @Override + public Map> getSchemas() { + return Fruit.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Apple, Banana + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Apple.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Banana.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Apple, Banana"); + } + + /** + * Get the actual instance, which can be the following: + * Apple, Banana + * + * @return The actual instance (Apple, Banana) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Apple`. If the actual instance is not `Apple`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Apple` + * @throws ClassCastException if the instance is not `Apple` + */ + @SuppressWarnings("unchecked") + public Apple getApple() throws ClassCastException { + return (Apple)super.getActualInstance(); + } + + /** + * Get the actual instance of `Banana`. If the actual instance is not `Banana`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Banana` + * @throws ClassCastException if the instance is not `Banana` + */ + @SuppressWarnings("unchecked") + public Banana getBanana() throws ClassCastException { + return (Banana)super.getActualInstance(); + } + + + + /** + * Create an instance of Fruit given an JSON string + * + * @param jsonString JSON string + * @return An instance of Fruit + * @throws IOException if the JSON string is invalid with respect to Fruit + */ + public static Fruit fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Fruit.class); + } + + /** + * Convert an instance of Fruit to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FruitReq.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FruitReq.java new file mode 100644 index 000000000000..324922b98fed --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/FruitReq.java @@ -0,0 +1,279 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class FruitReq extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(FruitReq.class.getName()); + + + /** + * 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 FruitReq + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize AppleReq + try { + // validate the JSON object to see if any exception is thrown + AppleReq.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for AppleReq failed with `%s`.", e.getMessage())); + } + + // deserialize BananaReq + try { + // validate the JSON object to see if any exception is thrown + BananaReq.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BananaReq failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for FruitReq: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FruitReq.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FruitReq' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterAppleReq = gson.getDelegateAdapter(this, TypeToken.get(AppleReq.class)); + final TypeAdapter adapterBananaReq = gson.getDelegateAdapter(this, TypeToken.get(BananaReq.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FruitReq value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `AppleReq` + if (value.getActualInstance() instanceof AppleReq) { + element = adapterAppleReq.toJsonTree((AppleReq)value.getActualInstance()); + } + // check if the actual instance is of the type `BananaReq` + if (value.getActualInstance() instanceof BananaReq) { + element = adapterBananaReq.toJsonTree((BananaReq)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: AppleReq, BananaReq"); + } + + elementAdapter.write(out, element); + } + + @Override + public FruitReq read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize AppleReq + try { + // validate the JSON object to see if any exception is thrown + AppleReq.validateJsonElement(jsonElement); + actualAdapter = adapterAppleReq; + match++; + log.log(Level.FINER, "Input data matches schema 'AppleReq'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for AppleReq failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'AppleReq'", e); + } + + // deserialize BananaReq + try { + // validate the JSON object to see if any exception is thrown + BananaReq.validateJsonElement(jsonElement); + actualAdapter = adapterBananaReq; + match++; + log.log(Level.FINER, "Input data matches schema 'BananaReq'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BananaReq failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'BananaReq'", e); + } + + if (match == 1) { + FruitReq ret = new FruitReq(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for FruitReq: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public FruitReq() { + super("oneOf", Boolean.TRUE); + } + + public FruitReq(AppleReq o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public FruitReq(BananaReq o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("AppleReq", AppleReq.class); + schemas.put("BananaReq", BananaReq.class); + } + + @Override + public Map> getSchemas() { + return FruitReq.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * AppleReq, BananaReq + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(AppleReq.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(BananaReq.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be AppleReq, BananaReq"); + } + + /** + * Get the actual instance, which can be the following: + * AppleReq, BananaReq + * + * @return The actual instance (AppleReq, BananaReq) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `AppleReq`. If the actual instance is not `AppleReq`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `AppleReq` + * @throws ClassCastException if the instance is not `AppleReq` + */ + @SuppressWarnings("unchecked") + public AppleReq getAppleReq() throws ClassCastException { + return (AppleReq)super.getActualInstance(); + } + + /** + * Get the actual instance of `BananaReq`. If the actual instance is not `BananaReq`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `BananaReq` + * @throws ClassCastException if the instance is not `BananaReq` + */ + @SuppressWarnings("unchecked") + public BananaReq getBananaReq() throws ClassCastException { + return (BananaReq)super.getActualInstance(); + } + + + + /** + * Create an instance of FruitReq given an JSON string + * + * @param jsonString JSON string + * @return An instance of FruitReq + * @throws IOException if the JSON string is invalid with respect to FruitReq + */ + public static FruitReq fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FruitReq.class); + } + + /** + * Convert an instance of FruitReq to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/GmFruit.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/GmFruit.java new file mode 100644 index 000000000000..11ca86baca32 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/GmFruit.java @@ -0,0 +1,267 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class GmFruit extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(GmFruit.class.getName()); + + + /** + * 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 GmFruit + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + try { + // validate the JSON object to see if any exception is thrown + Apple.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Apple failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + Banana.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Banana failed with `%s`.", e.getMessage())); + } + + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for GmFruit: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!GmFruit.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'GmFruit' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterApple = gson.getDelegateAdapter(this, TypeToken.get(Apple.class)); + final TypeAdapter adapterBanana = gson.getDelegateAdapter(this, TypeToken.get(Banana.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, GmFruit value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Apple` + if (value.getActualInstance() instanceof Apple) { + element = adapterApple.toJsonTree((Apple)value.getActualInstance()); + } + // check if the actual instance is of the type `Banana` + if (value.getActualInstance() instanceof Banana) { + element = adapterBanana.toJsonTree((Banana)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Apple, Banana"); + } + + elementAdapter.write(out, element); + } + + @Override + public GmFruit read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize Apple + try { + // validate the JSON object to see if any exception is thrown + Apple.validateJsonElement(jsonElement); + GmFruit ret = new GmFruit(); + ret.setActualInstance(adapterApple.fromJsonTree(jsonElement)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Apple failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Apple'", e); + } + + // deserialize Banana + try { + // validate the JSON object to see if any exception is thrown + Banana.validateJsonElement(jsonElement); + GmFruit ret = new GmFruit(); + ret.setActualInstance(adapterBanana.fromJsonTree(jsonElement)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Banana failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Banana'", e); + } + + + throw new IOException(String.format("Failed deserialization for GmFruit: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public GmFruit() { + super("anyOf", Boolean.FALSE); + } + + public GmFruit(Apple o) { + super("anyOf", Boolean.TRUE); + setActualInstance(o); + } + + public GmFruit(Banana o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Apple", Apple.class); + schemas.put("Banana", Banana.class); + } + + @Override + public Map> getSchemas() { + return GmFruit.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * Apple, Banana + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Apple.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Banana.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Apple, Banana"); + } + + /** + * Get the actual instance, which can be the following: + * Apple, Banana + * + * @return The actual instance (Apple, Banana) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Apple`. If the actual instance is not `Apple`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Apple` + * @throws ClassCastException if the instance is not `Apple` + */ + @SuppressWarnings("unchecked") + public Apple getApple() throws ClassCastException { + return (Apple)super.getActualInstance(); + } + + /** + * Get the actual instance of `Banana`. If the actual instance is not `Banana`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Banana` + * @throws ClassCastException if the instance is not `Banana` + */ + @SuppressWarnings("unchecked") + public Banana getBanana() throws ClassCastException { + return (Banana)super.getActualInstance(); + } + + + + /** + * Create an instance of GmFruit given an JSON string + * + * @param jsonString JSON string + * @return An instance of GmFruit + * @throws IOException if the JSON string is invalid with respect to GmFruit + */ + public static GmFruit fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, GmFruit.class); + } + + /** + * Convert an instance of GmFruit to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/GrandparentAnimal.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/GrandparentAnimal.java new file mode 100644 index 000000000000..0f50b1df97e6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/GrandparentAnimal.java @@ -0,0 +1,209 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * GrandparentAnimal + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class GrandparentAnimal { + public static final String SERIALIZED_NAME_PET_TYPE = "pet_type"; + @SerializedName(SERIALIZED_NAME_PET_TYPE) + @javax.annotation.Nonnull + protected String petType; + + public GrandparentAnimal() { + this.petType = this.getClass().getSimpleName(); + } + + public GrandparentAnimal petType(@javax.annotation.Nonnull String petType) { + this.petType = petType; + return this; + } + + /** + * Get petType + * @return petType + */ + @javax.annotation.Nonnull + + public String getPetType() { + return petType; + } + + public void setPetType(@javax.annotation.Nonnull String petType) { + this.petType = petType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the GrandparentAnimal instance itself + */ + public GrandparentAnimal putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GrandparentAnimal grandparentAnimal = (GrandparentAnimal) o; + return Objects.equals(this.petType, grandparentAnimal.petType)&& + Objects.equals(this.additionalProperties, grandparentAnimal.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(petType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class GrandparentAnimal {\n"); + sb.append(" petType: ").append(toIndentedString(petType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("pet_type")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("pet_type")); + } + + /** + * 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 GrandparentAnimal + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!GrandparentAnimal.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in GrandparentAnimal is not found in the empty JSON string", GrandparentAnimal.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + String discriminatorValue = jsonElement.getAsJsonObject().get("pet_type").getAsString(); + switch (discriminatorValue) { + case "ParentPet": + ParentPet.validateJsonElement(jsonElement); + break; + default: + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The value of the `pet_type` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue)); + } + } + + + /** + * Create an instance of GrandparentAnimal given an JSON string + * + * @param jsonString JSON string + * @return An instance of GrandparentAnimal + * @throws IOException if the JSON string is invalid with respect to GrandparentAnimal + */ + public static GrandparentAnimal fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, GrandparentAnimal.class); + } + + /** + * Convert an instance of GrandparentAnimal to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java new file mode 100644 index 000000000000..9bec6f6cb26a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -0,0 +1,302 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * HasOnlyReadOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class HasOnlyReadOnly { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + @javax.annotation.Nullable + private String bar; + + public static final String SERIALIZED_NAME_FOO = "foo"; + @SerializedName(SERIALIZED_NAME_FOO) + @javax.annotation.Nullable + private String foo; + + public HasOnlyReadOnly() { + } + + /** + * Constructor with only readonly parameters + */ + public HasOnlyReadOnly( + String bar, + String foo + ) { + this(); + this.bar = bar; + this.foo = foo; + } + + /** + * Get bar + * @return bar + */ + @javax.annotation.Nullable + + public String getBar() { + return bar; + } + + + + /** + * Get foo + * @return foo + */ + @javax.annotation.Nullable + + public String getFoo() { + return foo; + } + + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the HasOnlyReadOnly instance itself + */ + public HasOnlyReadOnly putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo)&& + Objects.equals(this.additionalProperties, hasOnlyReadOnly.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("bar", "foo")); + + // 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 HasOnlyReadOnly + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in HasOnlyReadOnly is not found in the empty JSON string", HasOnlyReadOnly.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); + } + if ((jsonObj.get("foo") != null && !jsonObj.get("foo").isJsonNull()) && !jsonObj.get("foo").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `foo` to be a primitive type in the JSON string but got `%s`", jsonObj.get("foo").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!HasOnlyReadOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'HasOnlyReadOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(HasOnlyReadOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, HasOnlyReadOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public HasOnlyReadOnly read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + HasOnlyReadOnly instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of HasOnlyReadOnly given an JSON string + * + * @param jsonString JSON string + * @return An instance of HasOnlyReadOnly + * @throws IOException if the JSON string is invalid with respect to HasOnlyReadOnly + */ + public static HasOnlyReadOnly fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, HasOnlyReadOnly.class); + } + + /** + * Convert an instance of HasOnlyReadOnly to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/HealthCheckResult.java new file mode 100644 index 000000000000..6aed9d5b5bf3 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -0,0 +1,276 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class HealthCheckResult { + public static final String SERIALIZED_NAME_NULLABLE_MESSAGE = "NullableMessage"; + @SerializedName(SERIALIZED_NAME_NULLABLE_MESSAGE) + @javax.annotation.Nullable + private String nullableMessage; + + public HealthCheckResult() { + } + + public HealthCheckResult nullableMessage(@javax.annotation.Nullable String nullableMessage) { + this.nullableMessage = nullableMessage; + return this; + } + + /** + * Get nullableMessage + * @return nullableMessage + */ + @javax.annotation.Nullable + + public String getNullableMessage() { + return nullableMessage; + } + + public void setNullableMessage(@javax.annotation.Nullable String nullableMessage) { + this.nullableMessage = nullableMessage; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the HealthCheckResult instance itself + */ + public HealthCheckResult putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HealthCheckResult healthCheckResult = (HealthCheckResult) o; + return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage)&& + Objects.equals(this.additionalProperties, healthCheckResult.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(nullableMessage, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthCheckResult {\n"); + sb.append(" nullableMessage: ").append(toIndentedString(nullableMessage)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("NullableMessage")); + + // 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 HealthCheckResult + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!HealthCheckResult.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in HealthCheckResult is not found in the empty JSON string", HealthCheckResult.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("NullableMessage") != null && !jsonObj.get("NullableMessage").isJsonNull()) && !jsonObj.get("NullableMessage").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `NullableMessage` to be a primitive type in the JSON string but got `%s`", jsonObj.get("NullableMessage").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!HealthCheckResult.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'HealthCheckResult' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(HealthCheckResult.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, HealthCheckResult value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public HealthCheckResult read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + HealthCheckResult instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of HealthCheckResult given an JSON string + * + * @param jsonString JSON string + * @return An instance of HealthCheckResult + * @throws IOException if the JSON string is invalid with respect to HealthCheckResult + */ + public static HealthCheckResult fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, HealthCheckResult.class); + } + + /** + * Convert an instance of HealthCheckResult to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java new file mode 100644 index 000000000000..4fbb3ec3a987 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java @@ -0,0 +1,228 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * IsoscelesTriangle + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class IsoscelesTriangle { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + @javax.annotation.Nonnull + private String shapeType; + + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + @javax.annotation.Nonnull + private String triangleType; + + public IsoscelesTriangle() { + } + + public IsoscelesTriangle shapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + */ + @javax.annotation.Nonnull + + public String getShapeType() { + return shapeType; + } + + public void setShapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + } + + + public IsoscelesTriangle triangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + */ + @javax.annotation.Nonnull + + public String getTriangleType() { + return triangleType; + } + + public void setTriangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + IsoscelesTriangle isoscelesTriangle = (IsoscelesTriangle) o; + return Objects.equals(this.shapeType, isoscelesTriangle.shapeType) && + Objects.equals(this.triangleType, isoscelesTriangle.triangleType); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, triangleType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class IsoscelesTriangle {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).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) { + return o == null ? "null" : 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("shapeType", "triangleType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("shapeType", "triangleType")); + } + + /** + * 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 IsoscelesTriangle + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!IsoscelesTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in IsoscelesTriangle is not found in the empty JSON string", IsoscelesTriangle.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!IsoscelesTriangle.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` in the JSON string is not defined in the `IsoscelesTriangle` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : IsoscelesTriangle.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("shapeType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); + } + if (!jsonObj.get("triangleType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!IsoscelesTriangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'IsoscelesTriangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(IsoscelesTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, IsoscelesTriangle value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public IsoscelesTriangle read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of IsoscelesTriangle given an JSON string + * + * @param jsonString JSON string + * @return An instance of IsoscelesTriangle + * @throws IOException if the JSON string is invalid with respect to IsoscelesTriangle + */ + public static IsoscelesTriangle fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, IsoscelesTriangle.class); + } + + /** + * Convert an instance of IsoscelesTriangle to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Mammal.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Mammal.java new file mode 100644 index 000000000000..d88a4f7addca --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Mammal.java @@ -0,0 +1,468 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Mammal extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Mammal.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Mammal instance itself + */ + public Mammal putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(Mammal instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(Mammal value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 Mammal + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("className") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'className' is missing."); + } + String discriminatorValue = jsonObject.get("className").getAsString(); + if ("Pig".equals(discriminatorValue)) { + Pig.validateJsonElement(jsonElement); + return; + } + if ("whale".equals(discriminatorValue)) { + Whale.validateJsonElement(jsonElement); + return; + } + if ("zebra".equals(discriminatorValue)) { + Zebra.validateJsonElement(jsonElement); + return; + } + // deserialize Whale + try { + // validate the JSON object to see if any exception is thrown + Whale.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Whale failed with `%s`.", e.getMessage())); + } + + // deserialize Zebra + try { + // validate the JSON object to see if any exception is thrown + Zebra.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Zebra failed with `%s`.", e.getMessage())); + } + + // deserialize Pig + try { + // validate the JSON object to see if any exception is thrown + Pig.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Mammal: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Mammal.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Mammal' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterWhale = gson.getDelegateAdapter(this, TypeToken.get(Whale.class)); + final TypeAdapter adapterZebra = gson.getDelegateAdapter(this, TypeToken.get(Zebra.class)); + final TypeAdapter adapterPig = gson.getDelegateAdapter(this, TypeToken.get(Pig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Mammal value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Whale` + if (value.getActualInstance() instanceof Whale) { + element = adapterWhale.toJsonTree((Whale)value.getActualInstance()); + } + // check if the actual instance is of the type `Zebra` + if (value.getActualInstance() instanceof Zebra) { + element = adapterZebra.toJsonTree((Zebra)value.getActualInstance()); + } + // check if the actual instance is of the type `Pig` + if (value.getActualInstance() instanceof Pig) { + element = adapterPig.toJsonTree((Pig)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Pig, Whale, Zebra"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public Mammal read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("className") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'className' is missing."); + } + String discriminatorValue = jsonObject.get("className").getAsString(); + if ("Pig".equals(discriminatorValue)) { + deserialized = adapterPig.fromJsonTree(jsonElement); + Mammal ret = new Mammal(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("whale".equals(discriminatorValue)) { + deserialized = adapterWhale.fromJsonTree(jsonElement); + Mammal ret = new Mammal(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("zebra".equals(discriminatorValue)) { + deserialized = adapterZebra.fromJsonTree(jsonElement); + Mammal ret = new Mammal(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Whale + try { + // validate the JSON object to see if any exception is thrown + Whale.validateJsonElement(jsonElement); + actualAdapter = adapterWhale; + match++; + log.log(Level.FINER, "Input data matches schema 'Whale'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Whale failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Whale'", e); + } + + // deserialize Zebra + try { + // validate the JSON object to see if any exception is thrown + Zebra.validateJsonElement(jsonElement); + actualAdapter = adapterZebra; + match++; + log.log(Level.FINER, "Input data matches schema 'Zebra'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Zebra failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Zebra'", e); + } + + // deserialize Pig + try { + // validate the JSON object to see if any exception is thrown + Pig.validateJsonElement(jsonElement); + actualAdapter = adapterPig; + match++; + log.log(Level.FINER, "Input data matches schema 'Pig'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Pig'", e); + } + + if (match == 1) { + Mammal ret = new Mammal(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Mammal: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Mammal() { + super("oneOf", Boolean.FALSE); + } + + public Mammal(Whale o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Mammal(Zebra o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Mammal(Pig o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Whale", Whale.class); + schemas.put("Zebra", Zebra.class); + schemas.put("Pig", Pig.class); + } + + @Override + public Map> getSchemas() { + return Mammal.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Pig, Whale, Zebra + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Whale.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Zebra.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Pig.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Pig, Whale, Zebra"); + } + + /** + * Get the actual instance, which can be the following: + * Pig, Whale, Zebra + * + * @return The actual instance (Pig, Whale, Zebra) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Whale`. If the actual instance is not `Whale`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Whale` + * @throws ClassCastException if the instance is not `Whale` + */ + @SuppressWarnings("unchecked") + public Whale getWhale() throws ClassCastException { + return (Whale)super.getActualInstance(); + } + + /** + * Get the actual instance of `Zebra`. If the actual instance is not `Zebra`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Zebra` + * @throws ClassCastException if the instance is not `Zebra` + */ + @SuppressWarnings("unchecked") + public Zebra getZebra() throws ClassCastException { + return (Zebra)super.getActualInstance(); + } + + /** + * Get the actual instance of `Pig`. If the actual instance is not `Pig`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Pig` + * @throws ClassCastException if the instance is not `Pig` + */ + @SuppressWarnings("unchecked") + public Pig getPig() throws ClassCastException { + return (Pig)super.getActualInstance(); + } + + + + /** + * Create an instance of Mammal given an JSON string + * + * @param jsonString JSON string + * @return An instance of Mammal + * @throws IOException if the JSON string is invalid with respect to Mammal + */ + public static Mammal fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Mammal.class); + } + + /** + * Convert an instance of Mammal to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MammalAnyof.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MammalAnyof.java new file mode 100644 index 000000000000..0f8a53c1ad8a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MammalAnyof.java @@ -0,0 +1,452 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class MammalAnyof extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(MammalAnyof.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the MammalAnyof instance itself + */ + public MammalAnyof putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(MammalAnyof instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched anyOf schema. + */ + private static void writeUnconsumedProperties(MammalAnyof value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 MammalAnyof + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + try { + // validate the JSON object to see if any exception is thrown + Whale.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Whale failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + Zebra.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Zebra failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + Pig.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage())); + } + + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for MammalAnyof: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!MammalAnyof.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'MammalAnyof' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterWhale = gson.getDelegateAdapter(this, TypeToken.get(Whale.class)); + final TypeAdapter adapterZebra = gson.getDelegateAdapter(this, TypeToken.get(Zebra.class)); + final TypeAdapter adapterPig = gson.getDelegateAdapter(this, TypeToken.get(Pig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, MammalAnyof value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Whale` + if (value.getActualInstance() instanceof Whale) { + element = adapterWhale.toJsonTree((Whale)value.getActualInstance()); + } + // check if the actual instance is of the type `Zebra` + if (value.getActualInstance() instanceof Zebra) { + element = adapterZebra.toJsonTree((Zebra)value.getActualInstance()); + } + // check if the actual instance is of the type `Pig` + if (value.getActualInstance() instanceof Pig) { + element = adapterPig.toJsonTree((Pig)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: Pig, Whale, Zebra"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public MammalAnyof read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + // non-object payloads can still match a non-object anyOf schema below + if (jsonElement.isJsonObject()) { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + JsonElement discriminatorElement = jsonObject.get("className"); + + // use discriminator value for faster anyOf lookup + MammalAnyof newMammalAnyof = new MammalAnyof(); + if (discriminatorElement == null || !discriminatorElement.isJsonPrimitive()) { + log.log(Level.WARNING, "Failed to lookup discriminator value for MammalAnyof as `className` is missing or is not a primitive type in the payload."); + } else { + // look up the discriminator value in the field `className` + switch (discriminatorElement.getAsString()) { + case "Pig": + deserialized = adapterPig.fromJsonTree(jsonObject); + newMammalAnyof.setActualInstance(deserialized); + collectUnconsumedProperties(newMammalAnyof, jsonElement, gson); + return newMammalAnyof; + case "whale": + deserialized = adapterWhale.fromJsonTree(jsonObject); + newMammalAnyof.setActualInstance(deserialized); + collectUnconsumedProperties(newMammalAnyof, jsonElement, gson); + return newMammalAnyof; + case "zebra": + deserialized = adapterZebra.fromJsonTree(jsonObject); + newMammalAnyof.setActualInstance(deserialized); + collectUnconsumedProperties(newMammalAnyof, jsonElement, gson); + return newMammalAnyof; + default: + log.log(Level.WARNING, String.format(java.util.Locale.ROOT, "Failed to lookup discriminator value `%s` for MammalAnyof. Possible values: Pig whale zebra", discriminatorElement.getAsString())); + } + } + } + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize Whale + try { + // validate the JSON object to see if any exception is thrown + Whale.validateJsonElement(jsonElement); + MammalAnyof ret = new MammalAnyof(); + ret.setActualInstance(adapterWhale.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Whale failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Whale'", e); + } + + // deserialize Zebra + try { + // validate the JSON object to see if any exception is thrown + Zebra.validateJsonElement(jsonElement); + MammalAnyof ret = new MammalAnyof(); + ret.setActualInstance(adapterZebra.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Zebra failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Zebra'", e); + } + + // deserialize Pig + try { + // validate the JSON object to see if any exception is thrown + Pig.validateJsonElement(jsonElement); + MammalAnyof ret = new MammalAnyof(); + ret.setActualInstance(adapterPig.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Pig'", e); + } + + + throw new IOException(String.format("Failed deserialization for MammalAnyof: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public MammalAnyof() { + super("anyOf", Boolean.FALSE); + } + + public MammalAnyof(Whale o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public MammalAnyof(Zebra o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public MammalAnyof(Pig o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Whale", Whale.class); + schemas.put("Zebra", Zebra.class); + schemas.put("Pig", Pig.class); + } + + @Override + public Map> getSchemas() { + return MammalAnyof.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * Pig, Whale, Zebra + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Whale.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Zebra.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Pig.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Pig, Whale, Zebra"); + } + + /** + * Get the actual instance, which can be the following: + * Pig, Whale, Zebra + * + * @return The actual instance (Pig, Whale, Zebra) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Whale`. If the actual instance is not `Whale`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Whale` + * @throws ClassCastException if the instance is not `Whale` + */ + @SuppressWarnings("unchecked") + public Whale getWhale() throws ClassCastException { + return (Whale)super.getActualInstance(); + } + + /** + * Get the actual instance of `Zebra`. If the actual instance is not `Zebra`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Zebra` + * @throws ClassCastException if the instance is not `Zebra` + */ + @SuppressWarnings("unchecked") + public Zebra getZebra() throws ClassCastException { + return (Zebra)super.getActualInstance(); + } + + /** + * Get the actual instance of `Pig`. If the actual instance is not `Pig`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Pig` + * @throws ClassCastException if the instance is not `Pig` + */ + @SuppressWarnings("unchecked") + public Pig getPig() throws ClassCastException { + return (Pig)super.getActualInstance(); + } + + + + /** + * Create an instance of MammalAnyof given an JSON string + * + * @param jsonString JSON string + * @return An instance of MammalAnyof + * @throws IOException if the JSON string is invalid with respect to MammalAnyof + */ + public static MammalAnyof fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, MammalAnyof.class); + } + + /** + * Convert an instance of MammalAnyof to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MapTest.java new file mode 100644 index 000000000000..4177849215c1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MapTest.java @@ -0,0 +1,439 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * MapTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class MapTest { + public static final String SERIALIZED_NAME_MAP_MAP_OF_STRING = "map_map_of_string"; + @SerializedName(SERIALIZED_NAME_MAP_MAP_OF_STRING) + @javax.annotation.Nullable + private Map> mapMapOfString = new HashMap<>(); + + /** + * Gets or Sets inner + */ + @JsonAdapter(InnerEnum.Adapter.class) + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static InnerEnum fromValue(String value) { + for (InnerEnum b : InnerEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final InnerEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public InnerEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return InnerEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + InnerEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_MAP_OF_ENUM_STRING = "map_of_enum_string"; + @SerializedName(SERIALIZED_NAME_MAP_OF_ENUM_STRING) + @javax.annotation.Nullable + private Map mapOfEnumString = new HashMap<>(); + + public static final String SERIALIZED_NAME_DIRECT_MAP = "direct_map"; + @SerializedName(SERIALIZED_NAME_DIRECT_MAP) + @javax.annotation.Nullable + private Map directMap = new HashMap<>(); + + public static final String SERIALIZED_NAME_INDIRECT_MAP = "indirect_map"; + @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) + @javax.annotation.Nullable + private Map indirectMap = new HashMap<>(); + + public MapTest() { + } + + public MapTest mapMapOfString(@javax.annotation.Nullable Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + if (this.mapMapOfString == null) { + this.mapMapOfString = new HashMap<>(); + } + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + */ + @javax.annotation.Nullable + + public Map> getMapMapOfString() { + return mapMapOfString; + } + + public void setMapMapOfString(@javax.annotation.Nullable Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + + public MapTest mapOfEnumString(@javax.annotation.Nullable Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + if (this.mapOfEnumString == null) { + this.mapOfEnumString = new HashMap<>(); + } + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + */ + @javax.annotation.Nullable + + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + public void setMapOfEnumString(@javax.annotation.Nullable Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + public MapTest directMap(@javax.annotation.Nullable Map directMap) { + this.directMap = directMap; + return this; + } + + public MapTest putDirectMapItem(String key, Boolean directMapItem) { + if (this.directMap == null) { + this.directMap = new HashMap<>(); + } + this.directMap.put(key, directMapItem); + return this; + } + + /** + * Get directMap + * @return directMap + */ + @javax.annotation.Nullable + + public Map getDirectMap() { + return directMap; + } + + public void setDirectMap(@javax.annotation.Nullable Map directMap) { + this.directMap = directMap; + } + + + public MapTest indirectMap(@javax.annotation.Nullable Map indirectMap) { + this.indirectMap = indirectMap; + return this; + } + + public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { + if (this.indirectMap == null) { + this.indirectMap = new HashMap<>(); + } + this.indirectMap.put(key, indirectMapItem); + return this; + } + + /** + * Get indirectMap + * @return indirectMap + */ + @javax.annotation.Nullable + + public Map getIndirectMap() { + return indirectMap; + } + + public void setIndirectMap(@javax.annotation.Nullable Map indirectMap) { + this.indirectMap = indirectMap; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the MapTest instance itself + */ + public MapTest putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap)&& + Objects.equals(this.additionalProperties, mapTest.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString, directMap, indirectMap, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("map_map_of_string", "map_of_enum_string", "direct_map", "indirect_map")); + + // 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 MapTest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!MapTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in MapTest is not found in the empty JSON string", MapTest.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!MapTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'MapTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(MapTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, MapTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public MapTest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + MapTest instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of MapTest given an JSON string + * + * @param jsonString JSON string + * @return An instance of MapTest + * @throws IOException if the JSON string is invalid with respect to MapTest + */ + public static MapTest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, MapTest.class); + } + + /** + * Convert an instance of MapTest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 000000000000..f832c3dc0c91 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,340 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class MixedPropertiesAndAdditionalPropertiesClass { + public static final String SERIALIZED_NAME_UUID = "uuid"; + @SerializedName(SERIALIZED_NAME_UUID) + @javax.annotation.Nullable + private UUID uuid; + + public static final String SERIALIZED_NAME_DATE_TIME = "dateTime"; + @SerializedName(SERIALIZED_NAME_DATE_TIME) + @javax.annotation.Nullable + private OffsetDateTime dateTime; + + public static final String SERIALIZED_NAME_MAP = "map"; + @SerializedName(SERIALIZED_NAME_MAP) + @javax.annotation.Nullable + private Map map = new HashMap<>(); + + public MixedPropertiesAndAdditionalPropertiesClass() { + } + + public MixedPropertiesAndAdditionalPropertiesClass uuid(@javax.annotation.Nullable UUID uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + */ + @javax.annotation.Nullable + + public UUID getUuid() { + return uuid; + } + + public void setUuid(@javax.annotation.Nullable UUID uuid) { + this.uuid = uuid; + } + + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(@javax.annotation.Nullable OffsetDateTime dateTime) { + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + */ + @javax.annotation.Nullable + + public OffsetDateTime getDateTime() { + return dateTime; + } + + public void setDateTime(@javax.annotation.Nullable OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + + public MixedPropertiesAndAdditionalPropertiesClass map(@javax.annotation.Nullable Map map) { + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + if (this.map == null) { + this.map = new HashMap<>(); + } + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + */ + @javax.annotation.Nullable + + public Map getMap() { + return map; + } + + public void setMap(@javax.annotation.Nullable Map map) { + this.map = map; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the MixedPropertiesAndAdditionalPropertiesClass instance itself + */ + public MixedPropertiesAndAdditionalPropertiesClass putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map)&& + Objects.equals(this.additionalProperties, mixedPropertiesAndAdditionalPropertiesClass.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("uuid", "dateTime", "map")); + + // 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 MixedPropertiesAndAdditionalPropertiesClass + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in MixedPropertiesAndAdditionalPropertiesClass is not found in the empty JSON string", MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!MixedPropertiesAndAdditionalPropertiesClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'MixedPropertiesAndAdditionalPropertiesClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(MixedPropertiesAndAdditionalPropertiesClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, MixedPropertiesAndAdditionalPropertiesClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public MixedPropertiesAndAdditionalPropertiesClass read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + MixedPropertiesAndAdditionalPropertiesClass instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of MixedPropertiesAndAdditionalPropertiesClass given an JSON string + * + * @param jsonString JSON string + * @return An instance of MixedPropertiesAndAdditionalPropertiesClass + * @throws IOException if the JSON string is invalid with respect to MixedPropertiesAndAdditionalPropertiesClass + */ + public static MixedPropertiesAndAdditionalPropertiesClass fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, MixedPropertiesAndAdditionalPropertiesClass.class); + } + + /** + * Convert an instance of MixedPropertiesAndAdditionalPropertiesClass to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Model200Response.java new file mode 100644 index 000000000000..3f37d2267959 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Model200Response.java @@ -0,0 +1,303 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Model for testing model name starting with number + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Model200Response { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nullable + private Integer name; + + public static final String SERIALIZED_NAME_PROPERTY_CLASS = "class"; + @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) + @javax.annotation.Nullable + private String propertyClass; + + public Model200Response() { + } + + public Model200Response name(@javax.annotation.Nullable Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nullable + + public Integer getName() { + return name; + } + + public void setName(@javax.annotation.Nullable Integer name) { + this.name = name; + } + + + public Model200Response propertyClass(@javax.annotation.Nullable String propertyClass) { + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + */ + @javax.annotation.Nullable + + public String getPropertyClass() { + return propertyClass; + } + + public void setPropertyClass(@javax.annotation.Nullable String propertyClass) { + this.propertyClass = propertyClass; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Model200Response instance itself + */ + public Model200Response putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200response = (Model200Response) o; + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass)&& + Objects.equals(this.additionalProperties, _200response.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("name", "class")); + + // 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 Model200Response + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Model200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Model200Response is not found in the empty JSON string", Model200Response.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("class") != null && !jsonObj.get("class").isJsonNull()) && !jsonObj.get("class").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("class").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Model200Response.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Model200Response' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Model200Response.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Model200Response value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Model200Response read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Model200Response instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Model200Response given an JSON string + * + * @param jsonString JSON string + * @return An instance of Model200Response + * @throws IOException if the JSON string is invalid with respect to Model200Response + */ + public static Model200Response fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Model200Response.class); + } + + /** + * Convert an instance of Model200Response to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelApiResponse.java new file mode 100644 index 000000000000..c52b8c13c219 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -0,0 +1,333 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ModelApiResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ModelApiResponse { + public static final String SERIALIZED_NAME_CODE = "code"; + @SerializedName(SERIALIZED_NAME_CODE) + @javax.annotation.Nullable + private Integer code; + + public static final String SERIALIZED_NAME_TYPE = "type"; + @SerializedName(SERIALIZED_NAME_TYPE) + @javax.annotation.Nullable + private String type; + + public static final String SERIALIZED_NAME_MESSAGE = "message"; + @SerializedName(SERIALIZED_NAME_MESSAGE) + @javax.annotation.Nullable + private String message; + + public ModelApiResponse() { + } + + public ModelApiResponse code(@javax.annotation.Nullable Integer code) { + this.code = code; + return this; + } + + /** + * Get code + * @return code + */ + @javax.annotation.Nullable + + public Integer getCode() { + return code; + } + + public void setCode(@javax.annotation.Nullable Integer code) { + this.code = code; + } + + + public ModelApiResponse type(@javax.annotation.Nullable String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @javax.annotation.Nullable + + public String getType() { + return type; + } + + public void setType(@javax.annotation.Nullable String type) { + this.type = type; + } + + + public ModelApiResponse message(@javax.annotation.Nullable String message) { + this.message = message; + return this; + } + + /** + * Get message + * @return message + */ + @javax.annotation.Nullable + + public String getMessage() { + return message; + } + + public void setMessage(@javax.annotation.Nullable String message) { + this.message = message; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ModelApiResponse instance itself + */ + public ModelApiResponse putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message)&& + Objects.equals(this.additionalProperties, _apiResponse.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("code", "type", "message")); + + // 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 ModelApiResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); + } + if ((jsonObj.get("message") != null && !jsonObj.get("message").isJsonNull()) && !jsonObj.get("message").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `message` to be a primitive type in the JSON string but got `%s`", jsonObj.get("message").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelApiResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelApiResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelApiResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelApiResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ModelApiResponse read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ModelApiResponse instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ModelApiResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of ModelApiResponse + * @throws IOException if the JSON string is invalid with respect to ModelApiResponse + */ + public static ModelApiResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ModelApiResponse.class); + } + + /** + * Convert an instance of ModelApiResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelFile.java new file mode 100644 index 000000000000..aa1e6e75d7bd --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelFile.java @@ -0,0 +1,276 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Must be named `File` for test. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ModelFile { + public static final String SERIALIZED_NAME_SOURCE_U_R_I = "sourceURI"; + @SerializedName(SERIALIZED_NAME_SOURCE_U_R_I) + @javax.annotation.Nullable + private String sourceURI; + + public ModelFile() { + } + + public ModelFile sourceURI(@javax.annotation.Nullable String sourceURI) { + this.sourceURI = sourceURI; + return this; + } + + /** + * Test capitalization + * @return sourceURI + */ + @javax.annotation.Nullable + + public String getSourceURI() { + return sourceURI; + } + + public void setSourceURI(@javax.annotation.Nullable String sourceURI) { + this.sourceURI = sourceURI; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ModelFile instance itself + */ + public ModelFile putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelFile _file = (ModelFile) o; + return Objects.equals(this.sourceURI, _file.sourceURI)&& + Objects.equals(this.additionalProperties, _file.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(sourceURI, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelFile {\n"); + sb.append(" sourceURI: ").append(toIndentedString(sourceURI)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("sourceURI")); + + // 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 ModelFile + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ModelFile.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ModelFile is not found in the empty JSON string", ModelFile.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonNull()) && !jsonObj.get("sourceURI").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `sourceURI` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sourceURI").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelFile.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelFile' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelFile.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelFile value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ModelFile read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ModelFile instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ModelFile given an JSON string + * + * @param jsonString JSON string + * @return An instance of ModelFile + * @throws IOException if the JSON string is invalid with respect to ModelFile + */ + public static ModelFile fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ModelFile.class); + } + + /** + * Convert an instance of ModelFile to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelList.java new file mode 100644 index 000000000000..e7dff7141f06 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelList.java @@ -0,0 +1,276 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ModelList + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ModelList { + public static final String SERIALIZED_NAME_123LIST = "123-list"; + @SerializedName(SERIALIZED_NAME_123LIST) + @javax.annotation.Nullable + private String _123list; + + public ModelList() { + } + + public ModelList _123list(@javax.annotation.Nullable String _123list) { + this._123list = _123list; + return this; + } + + /** + * Get _123list + * @return _123list + */ + @javax.annotation.Nullable + + public String get123list() { + return _123list; + } + + public void set123list(@javax.annotation.Nullable String _123list) { + this._123list = _123list; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ModelList instance itself + */ + public ModelList putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelList _list = (ModelList) o; + return Objects.equals(this._123list, _list._123list)&& + Objects.equals(this.additionalProperties, _list.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(_123list, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelList {\n"); + sb.append(" _123list: ").append(toIndentedString(_123list)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("123-list")); + + // 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 ModelList + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ModelList.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ModelList is not found in the empty JSON string", ModelList.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonNull()) && !jsonObj.get("123-list").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `123-list` to be a primitive type in the JSON string but got `%s`", jsonObj.get("123-list").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelList.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelList' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelList.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelList value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ModelList read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ModelList instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ModelList given an JSON string + * + * @param jsonString JSON string + * @return An instance of ModelList + * @throws IOException if the JSON string is invalid with respect to ModelList + */ + public static ModelList fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ModelList.class); + } + + /** + * Convert an instance of ModelList to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelReturn.java new file mode 100644 index 000000000000..e0232e38f97f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -0,0 +1,273 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Model for testing reserved words + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ModelReturn { + public static final String SERIALIZED_NAME_RETURN = "return"; + @SerializedName(SERIALIZED_NAME_RETURN) + @javax.annotation.Nullable + private Integer _return; + + public ModelReturn() { + } + + public ModelReturn _return(@javax.annotation.Nullable Integer _return) { + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + */ + @javax.annotation.Nullable + + public Integer getReturn() { + return _return; + } + + public void setReturn(@javax.annotation.Nullable Integer _return) { + this._return = _return; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ModelReturn instance itself + */ + public ModelReturn putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return)&& + Objects.equals(this.additionalProperties, _return.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(_return, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("return")); + + // 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 ModelReturn + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ModelReturn.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ModelReturn is not found in the empty JSON string", ModelReturn.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelReturn.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelReturn' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelReturn.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelReturn value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ModelReturn read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ModelReturn instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ModelReturn given an JSON string + * + * @param jsonString JSON string + * @return An instance of ModelReturn + * @throws IOException if the JSON string is invalid with respect to ModelReturn + */ + public static ModelReturn fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ModelReturn.class); + } + + /** + * Convert an instance of ModelReturn to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelWithOneOfAnyOfProperties.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelWithOneOfAnyOfProperties.java new file mode 100644 index 000000000000..caa03340245f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ModelWithOneOfAnyOfProperties.java @@ -0,0 +1,308 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ModelWithOneOfAnyOfProperties + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ModelWithOneOfAnyOfProperties { + public static final String SERIALIZED_NAME_ONEOF_PROP = "oneof_prop"; + @SerializedName(SERIALIZED_NAME_ONEOF_PROP) + @javax.annotation.Nullable + private ArrayOneOf oneofProp; + + public static final String SERIALIZED_NAME_ANYOF_PROP = "anyof_prop"; + @SerializedName(SERIALIZED_NAME_ANYOF_PROP) + @javax.annotation.Nullable + private ArrayAnyOf anyofProp; + + public ModelWithOneOfAnyOfProperties() { + } + + public ModelWithOneOfAnyOfProperties oneofProp(@javax.annotation.Nullable ArrayOneOf oneofProp) { + this.oneofProp = oneofProp; + return this; + } + + /** + * Get oneofProp + * @return oneofProp + */ + @javax.annotation.Nullable + + public ArrayOneOf getOneofProp() { + return oneofProp; + } + + public void setOneofProp(@javax.annotation.Nullable ArrayOneOf oneofProp) { + this.oneofProp = oneofProp; + } + + + public ModelWithOneOfAnyOfProperties anyofProp(@javax.annotation.Nullable ArrayAnyOf anyofProp) { + this.anyofProp = anyofProp; + return this; + } + + /** + * Get anyofProp + * @return anyofProp + */ + @javax.annotation.Nullable + + public ArrayAnyOf getAnyofProp() { + return anyofProp; + } + + public void setAnyofProp(@javax.annotation.Nullable ArrayAnyOf anyofProp) { + this.anyofProp = anyofProp; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ModelWithOneOfAnyOfProperties instance itself + */ + public ModelWithOneOfAnyOfProperties putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelWithOneOfAnyOfProperties modelWithOneOfAnyOfProperties = (ModelWithOneOfAnyOfProperties) o; + return Objects.equals(this.oneofProp, modelWithOneOfAnyOfProperties.oneofProp) && + Objects.equals(this.anyofProp, modelWithOneOfAnyOfProperties.anyofProp)&& + Objects.equals(this.additionalProperties, modelWithOneOfAnyOfProperties.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(oneofProp, anyofProp, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelWithOneOfAnyOfProperties {\n"); + sb.append(" oneofProp: ").append(toIndentedString(oneofProp)).append("\n"); + sb.append(" anyofProp: ").append(toIndentedString(anyofProp)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("oneof_prop", "anyof_prop")); + + // 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 ModelWithOneOfAnyOfProperties + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ModelWithOneOfAnyOfProperties.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ModelWithOneOfAnyOfProperties is not found in the empty JSON string", ModelWithOneOfAnyOfProperties.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `oneof_prop` + if (jsonObj.get("oneof_prop") != null && !jsonObj.get("oneof_prop").isJsonNull()) { + ArrayOneOf.validateJsonElement(jsonObj.get("oneof_prop")); + } + // validate the optional field `anyof_prop` + if (jsonObj.get("anyof_prop") != null && !jsonObj.get("anyof_prop").isJsonNull()) { + ArrayAnyOf.validateJsonElement(jsonObj.get("anyof_prop")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelWithOneOfAnyOfProperties.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelWithOneOfAnyOfProperties' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelWithOneOfAnyOfProperties.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelWithOneOfAnyOfProperties value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ModelWithOneOfAnyOfProperties read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ModelWithOneOfAnyOfProperties instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ModelWithOneOfAnyOfProperties given an JSON string + * + * @param jsonString JSON string + * @return An instance of ModelWithOneOfAnyOfProperties + * @throws IOException if the JSON string is invalid with respect to ModelWithOneOfAnyOfProperties + */ + public static ModelWithOneOfAnyOfProperties fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ModelWithOneOfAnyOfProperties.class); + } + + /** + * Convert an instance of ModelWithOneOfAnyOfProperties to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Name.java new file mode 100644 index 000000000000..004576b0bc3e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Name.java @@ -0,0 +1,360 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Model for testing model name same as property name + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Name { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private Integer name; + + public static final String SERIALIZED_NAME_SNAKE_CASE = "snake_case"; + @SerializedName(SERIALIZED_NAME_SNAKE_CASE) + @javax.annotation.Nullable + private Integer snakeCase; + + public static final String SERIALIZED_NAME_PROPERTY = "property"; + @SerializedName(SERIALIZED_NAME_PROPERTY) + @javax.annotation.Nullable + private String property; + + public static final String SERIALIZED_NAME_123NUMBER = "123Number"; + @SerializedName(SERIALIZED_NAME_123NUMBER) + @javax.annotation.Nullable + private Integer _123number; + + public Name() { + } + + /** + * Constructor with only readonly parameters + */ + public Name( + Integer snakeCase, + Integer _123number + ) { + this(); + this.snakeCase = snakeCase; + this._123number = _123number; + } + + public Name name(@javax.annotation.Nonnull Integer name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public Integer getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull Integer name) { + this.name = name; + } + + + /** + * Get snakeCase + * @return snakeCase + */ + @javax.annotation.Nullable + + public Integer getSnakeCase() { + return snakeCase; + } + + + + public Name property(@javax.annotation.Nullable String property) { + this.property = property; + return this; + } + + /** + * Get property + * @return property + */ + @javax.annotation.Nullable + + public String getProperty() { + return property; + } + + public void setProperty(@javax.annotation.Nullable String property) { + this.property = property; + } + + + /** + * Get _123number + * @return _123number + */ + @javax.annotation.Nullable + + public Integer get123number() { + return _123number; + } + + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Name instance itself + */ + public Name putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number)&& + Objects.equals(this.additionalProperties, name.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123number, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("name", "snake_case", "property", "123Number")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name")); + } + + /** + * 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 Name + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Name.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Name is not found in the empty JSON string", Name.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Name.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("property") != null && !jsonObj.get("property").isJsonNull()) && !jsonObj.get("property").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `property` to be a primitive type in the JSON string but got `%s`", jsonObj.get("property").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Name.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Name' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Name.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Name value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Name read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Name instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Name given an JSON string + * + * @param jsonString JSON string + * @return An instance of Name + * @throws IOException if the JSON string is invalid with respect to Name + */ + public static Name fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Name.class); + } + + /** + * Convert an instance of Name to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NestedArrayWithDefaultValues.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NestedArrayWithDefaultValues.java new file mode 100644 index 000000000000..c96dae82c90f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NestedArrayWithDefaultValues.java @@ -0,0 +1,291 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * NestedArrayWithDefaultValues + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NestedArrayWithDefaultValues { + public static final String SERIALIZED_NAME_NESTED_ARRAY = "nestedArray"; + @SerializedName(SERIALIZED_NAME_NESTED_ARRAY) + @javax.annotation.Nullable + private List> nestedArray = new ArrayList<>(Arrays.asList( + new ArrayList<>(Arrays.asList("h1", "Header 1")), + new ArrayList<>(Arrays.asList("h2", "Header 2")), + new ArrayList<>(Arrays.asList("h3", "Header 3")), + new ArrayList<>(Arrays.asList("h4", "Header 4")) + )); + + public NestedArrayWithDefaultValues() { + } + + public NestedArrayWithDefaultValues nestedArray(@javax.annotation.Nullable List> nestedArray) { + this.nestedArray = nestedArray; + return this; + } + + public NestedArrayWithDefaultValues addNestedArrayItem(List nestedArrayItem) { + if (this.nestedArray == null) { + this.nestedArray = new ArrayList<>(); + } + this.nestedArray.add(nestedArrayItem); + return this; + } + + /** + * Get nestedArray + * @return nestedArray + */ + @javax.annotation.Nullable + + public List> getNestedArray() { + return nestedArray; + } + + public void setNestedArray(@javax.annotation.Nullable List> nestedArray) { + this.nestedArray = nestedArray; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NestedArrayWithDefaultValues instance itself + */ + public NestedArrayWithDefaultValues putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NestedArrayWithDefaultValues nestedArrayWithDefaultValues = (NestedArrayWithDefaultValues) o; + return Objects.equals(this.nestedArray, nestedArrayWithDefaultValues.nestedArray)&& + Objects.equals(this.additionalProperties, nestedArrayWithDefaultValues.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(nestedArray, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NestedArrayWithDefaultValues {\n"); + sb.append(" nestedArray: ").append(toIndentedString(nestedArray)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("nestedArray")); + + // 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 NestedArrayWithDefaultValues + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NestedArrayWithDefaultValues.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NestedArrayWithDefaultValues is not found in the empty JSON string", NestedArrayWithDefaultValues.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("nestedArray") != null && !jsonObj.get("nestedArray").isJsonNull() && !jsonObj.get("nestedArray").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `nestedArray` to be an array in the JSON string but got `%s`", jsonObj.get("nestedArray").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NestedArrayWithDefaultValues.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NestedArrayWithDefaultValues' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NestedArrayWithDefaultValues.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NestedArrayWithDefaultValues value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public NestedArrayWithDefaultValues read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NestedArrayWithDefaultValues instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NestedArrayWithDefaultValues given an JSON string + * + * @param jsonString JSON string + * @return An instance of NestedArrayWithDefaultValues + * @throws IOException if the JSON string is invalid with respect to NestedArrayWithDefaultValues + */ + public static NestedArrayWithDefaultValues fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NestedArrayWithDefaultValues.class); + } + + /** + * Convert an instance of NestedArrayWithDefaultValues to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPet.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPet.java new file mode 100644 index 000000000000..01f8777dac95 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPet.java @@ -0,0 +1,616 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * NewPet + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NewPet { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY_INLINE_ALLOF = "category_inline_allof"; + @SerializedName(SERIALIZED_NAME_CATEGORY_INLINE_ALLOF) + @javax.annotation.Nullable + private NewPetCategoryInlineAllof categoryInlineAllof; + + public static final String SERIALIZED_NAME_CATEGORY_ALL_OF_REF = "category_allOf_ref"; + @SerializedName(SERIALIZED_NAME_CATEGORY_ALL_OF_REF) + @javax.annotation.Nullable + private Category categoryAllOfRef; + + public static final String SERIALIZED_NAME_CATEGORY_ALL_OF_REF_DESCRIPTION = "category_allOf_ref_description"; + @SerializedName(SERIALIZED_NAME_CATEGORY_ALL_OF_REF_DESCRIPTION) + @javax.annotation.Nullable + private Category categoryAllOfRefDescription; + + public static final String SERIALIZED_NAME_CATEGORY_ALL_OF_REF_DESCRIPTION_READONLY = "category_allOf_ref_description_readonly"; + @SerializedName(SERIALIZED_NAME_CATEGORY_ALL_OF_REF_DESCRIPTION_READONLY) + @javax.annotation.Nullable + private Category categoryAllOfRefDescriptionReadonly; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + @javax.annotation.Nonnull + private List photoUrls = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + @javax.annotation.Nullable + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public NewPet() { + } + + /** + * Constructor with only readonly parameters + */ + public NewPet( + Category categoryAllOfRefDescriptionReadonly + ) { + this(); + this.categoryAllOfRefDescriptionReadonly = categoryAllOfRefDescriptionReadonly; + } + + public NewPet id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public NewPet categoryInlineAllof(@javax.annotation.Nullable NewPetCategoryInlineAllof categoryInlineAllof) { + this.categoryInlineAllof = categoryInlineAllof; + return this; + } + + /** + * Get categoryInlineAllof + * @return categoryInlineAllof + */ + @javax.annotation.Nullable + + public NewPetCategoryInlineAllof getCategoryInlineAllof() { + return categoryInlineAllof; + } + + public void setCategoryInlineAllof(@javax.annotation.Nullable NewPetCategoryInlineAllof categoryInlineAllof) { + this.categoryInlineAllof = categoryInlineAllof; + } + + + public NewPet categoryAllOfRef(@javax.annotation.Nullable Category categoryAllOfRef) { + this.categoryAllOfRef = categoryAllOfRef; + return this; + } + + /** + * Get categoryAllOfRef + * @return categoryAllOfRef + */ + @javax.annotation.Nullable + + public Category getCategoryAllOfRef() { + return categoryAllOfRef; + } + + public void setCategoryAllOfRef(@javax.annotation.Nullable Category categoryAllOfRef) { + this.categoryAllOfRef = categoryAllOfRef; + } + + + public NewPet categoryAllOfRefDescription(@javax.annotation.Nullable Category categoryAllOfRefDescription) { + this.categoryAllOfRefDescription = categoryAllOfRefDescription; + return this; + } + + /** + * Adding description to property using allOf + * @return categoryAllOfRefDescription + */ + @javax.annotation.Nullable + + public Category getCategoryAllOfRefDescription() { + return categoryAllOfRefDescription; + } + + public void setCategoryAllOfRefDescription(@javax.annotation.Nullable Category categoryAllOfRefDescription) { + this.categoryAllOfRefDescription = categoryAllOfRefDescription; + } + + + /** + * Adding description to readonly property using allOf + * @return categoryAllOfRefDescriptionReadonly + */ + @javax.annotation.Nullable + + public Category getCategoryAllOfRefDescriptionReadonly() { + return categoryAllOfRefDescriptionReadonly; + } + + + + public NewPet name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public NewPet photoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public NewPet addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @javax.annotation.Nonnull + + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + } + + + public NewPet tags(@javax.annotation.Nullable List tags) { + this.tags = tags; + return this; + } + + public NewPet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @javax.annotation.Nullable + + public List getTags() { + return tags; + } + + public void setTags(@javax.annotation.Nullable List tags) { + this.tags = tags; + } + + + public NewPet status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NewPet instance itself + */ + public NewPet putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NewPet newPet = (NewPet) o; + return Objects.equals(this.id, newPet.id) && + Objects.equals(this.categoryInlineAllof, newPet.categoryInlineAllof) && + Objects.equals(this.categoryAllOfRef, newPet.categoryAllOfRef) && + Objects.equals(this.categoryAllOfRefDescription, newPet.categoryAllOfRefDescription) && + Objects.equals(this.categoryAllOfRefDescriptionReadonly, newPet.categoryAllOfRefDescriptionReadonly) && + Objects.equals(this.name, newPet.name) && + Objects.equals(this.photoUrls, newPet.photoUrls) && + Objects.equals(this.tags, newPet.tags) && + Objects.equals(this.status, newPet.status)&& + Objects.equals(this.additionalProperties, newPet.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, categoryInlineAllof, categoryAllOfRef, categoryAllOfRefDescription, categoryAllOfRefDescriptionReadonly, name, photoUrls, tags, status, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NewPet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" categoryInlineAllof: ").append(toIndentedString(categoryInlineAllof)).append("\n"); + sb.append(" categoryAllOfRef: ").append(toIndentedString(categoryAllOfRef)).append("\n"); + sb.append(" categoryAllOfRefDescription: ").append(toIndentedString(categoryAllOfRefDescription)).append("\n"); + sb.append(" categoryAllOfRefDescriptionReadonly: ").append(toIndentedString(categoryAllOfRefDescriptionReadonly)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "category_inline_allof", "category_allOf_ref", "category_allOf_ref_description", "category_allOf_ref_description_readonly", "name", "photoUrls", "tags", "status")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "photoUrls")); + } + + /** + * 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 NewPet + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NewPet.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NewPet is not found in the empty JSON string", NewPet.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : NewPet.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `category_inline_allof` + if (jsonObj.get("category_inline_allof") != null && !jsonObj.get("category_inline_allof").isJsonNull()) { + NewPetCategoryInlineAllof.validateJsonElement(jsonObj.get("category_inline_allof")); + } + // validate the optional field `category_allOf_ref` + if (jsonObj.get("category_allOf_ref") != null && !jsonObj.get("category_allOf_ref").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category_allOf_ref")); + } + // validate the optional field `category_allOf_ref_description` + if (jsonObj.get("category_allOf_ref_description") != null && !jsonObj.get("category_allOf_ref_description").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category_allOf_ref_description")); + } + // validate the optional field `category_allOf_ref_description_readonly` + if (jsonObj.get("category_allOf_ref_description_readonly") != null && !jsonObj.get("category_allOf_ref_description_readonly").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category_allOf_ref_description_readonly")); + } + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // ensure the required json array is present + if (jsonObj.get("photoUrls") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("photoUrls").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); + } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + com.google.gson.JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + }; + } + } + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NewPet.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NewPet' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NewPet.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NewPet value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public NewPet read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NewPet instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NewPet given an JSON string + * + * @param jsonString JSON string + * @return An instance of NewPet + * @throws IOException if the JSON string is invalid with respect to NewPet + */ + public static NewPet fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NewPet.class); + } + + /** + * Convert an instance of NewPet to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java new file mode 100644 index 000000000000..dc4f170263e0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java @@ -0,0 +1,341 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * NewPetCategoryInlineAllof + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NewPetCategoryInlineAllof { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name = "default-name"; + + public static final String SERIALIZED_NAME_CATEGORY_TAG = "category_tag"; + @SerializedName(SERIALIZED_NAME_CATEGORY_TAG) + @javax.annotation.Nullable + private NewPetCategoryInlineAllofAllOfCategoryTag categoryTag; + + public NewPetCategoryInlineAllof() { + } + + public NewPetCategoryInlineAllof id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public NewPetCategoryInlineAllof name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public NewPetCategoryInlineAllof categoryTag(@javax.annotation.Nullable NewPetCategoryInlineAllofAllOfCategoryTag categoryTag) { + this.categoryTag = categoryTag; + return this; + } + + /** + * Get categoryTag + * @return categoryTag + */ + @javax.annotation.Nullable + + public NewPetCategoryInlineAllofAllOfCategoryTag getCategoryTag() { + return categoryTag; + } + + public void setCategoryTag(@javax.annotation.Nullable NewPetCategoryInlineAllofAllOfCategoryTag categoryTag) { + this.categoryTag = categoryTag; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NewPetCategoryInlineAllof instance itself + */ + public NewPetCategoryInlineAllof putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NewPetCategoryInlineAllof newPetCategoryInlineAllof = (NewPetCategoryInlineAllof) o; + return Objects.equals(this.id, newPetCategoryInlineAllof.id) && + Objects.equals(this.name, newPetCategoryInlineAllof.name) && + Objects.equals(this.categoryTag, newPetCategoryInlineAllof.categoryTag)&& + Objects.equals(this.additionalProperties, newPetCategoryInlineAllof.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, categoryTag, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NewPetCategoryInlineAllof {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" categoryTag: ").append(toIndentedString(categoryTag)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name", "category_tag")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name")); + } + + /** + * 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 NewPetCategoryInlineAllof + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NewPetCategoryInlineAllof.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NewPetCategoryInlineAllof is not found in the empty JSON string", NewPetCategoryInlineAllof.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : NewPetCategoryInlineAllof.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // validate the optional field `category_tag` + if (jsonObj.get("category_tag") != null && !jsonObj.get("category_tag").isJsonNull()) { + NewPetCategoryInlineAllofAllOfCategoryTag.validateJsonElement(jsonObj.get("category_tag")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NewPetCategoryInlineAllof.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NewPetCategoryInlineAllof' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NewPetCategoryInlineAllof.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NewPetCategoryInlineAllof value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public NewPetCategoryInlineAllof read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NewPetCategoryInlineAllof instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NewPetCategoryInlineAllof given an JSON string + * + * @param jsonString JSON string + * @return An instance of NewPetCategoryInlineAllof + * @throws IOException if the JSON string is invalid with respect to NewPetCategoryInlineAllof + */ + public static NewPetCategoryInlineAllof fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NewPetCategoryInlineAllof.class); + } + + /** + * Convert an instance of NewPetCategoryInlineAllof to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java new file mode 100644 index 000000000000..9aaff584ac3c --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java @@ -0,0 +1,303 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * NewPetCategoryInlineAllofAllOfCategoryTag + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NewPetCategoryInlineAllofAllOfCategoryTag { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nullable + private String name; + + public NewPetCategoryInlineAllofAllOfCategoryTag() { + } + + public NewPetCategoryInlineAllofAllOfCategoryTag id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public NewPetCategoryInlineAllofAllOfCategoryTag name(@javax.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nullable + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nullable String name) { + this.name = name; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NewPetCategoryInlineAllofAllOfCategoryTag instance itself + */ + public NewPetCategoryInlineAllofAllOfCategoryTag putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NewPetCategoryInlineAllofAllOfCategoryTag newPetCategoryInlineAllofAllOfCategoryTag = (NewPetCategoryInlineAllofAllOfCategoryTag) o; + return Objects.equals(this.id, newPetCategoryInlineAllofAllOfCategoryTag.id) && + Objects.equals(this.name, newPetCategoryInlineAllofAllOfCategoryTag.name)&& + Objects.equals(this.additionalProperties, newPetCategoryInlineAllofAllOfCategoryTag.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NewPetCategoryInlineAllofAllOfCategoryTag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name")); + + // 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 NewPetCategoryInlineAllofAllOfCategoryTag + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NewPetCategoryInlineAllofAllOfCategoryTag.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NewPetCategoryInlineAllofAllOfCategoryTag is not found in the empty JSON string", NewPetCategoryInlineAllofAllOfCategoryTag.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NewPetCategoryInlineAllofAllOfCategoryTag.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NewPetCategoryInlineAllofAllOfCategoryTag' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NewPetCategoryInlineAllofAllOfCategoryTag.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NewPetCategoryInlineAllofAllOfCategoryTag value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public NewPetCategoryInlineAllofAllOfCategoryTag read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NewPetCategoryInlineAllofAllOfCategoryTag instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NewPetCategoryInlineAllofAllOfCategoryTag given an JSON string + * + * @param jsonString JSON string + * @return An instance of NewPetCategoryInlineAllofAllOfCategoryTag + * @throws IOException if the JSON string is invalid with respect to NewPetCategoryInlineAllofAllOfCategoryTag + */ + public static NewPetCategoryInlineAllofAllOfCategoryTag fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NewPetCategoryInlineAllofAllOfCategoryTag.class); + } + + /** + * Convert an instance of NewPetCategoryInlineAllofAllOfCategoryTag to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableClass.java new file mode 100644 index 000000000000..d61cea5dcd44 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableClass.java @@ -0,0 +1,637 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * NullableClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NullableClass { + public static final String SERIALIZED_NAME_INTEGER_PROP = "integer_prop"; + @SerializedName(SERIALIZED_NAME_INTEGER_PROP) + @javax.annotation.Nullable + private Integer integerProp; + + public static final String SERIALIZED_NAME_NUMBER_PROP = "number_prop"; + @SerializedName(SERIALIZED_NAME_NUMBER_PROP) + @javax.annotation.Nullable + private BigDecimal numberProp; + + public static final String SERIALIZED_NAME_BOOLEAN_PROP = "boolean_prop"; + @SerializedName(SERIALIZED_NAME_BOOLEAN_PROP) + @javax.annotation.Nullable + private Boolean booleanProp; + + public static final String SERIALIZED_NAME_STRING_PROP = "string_prop"; + @SerializedName(SERIALIZED_NAME_STRING_PROP) + @javax.annotation.Nullable + private String stringProp; + + public static final String SERIALIZED_NAME_DATE_PROP = "date_prop"; + @SerializedName(SERIALIZED_NAME_DATE_PROP) + @javax.annotation.Nullable + private LocalDate dateProp; + + public static final String SERIALIZED_NAME_DATETIME_PROP = "datetime_prop"; + @SerializedName(SERIALIZED_NAME_DATETIME_PROP) + @javax.annotation.Nullable + private OffsetDateTime datetimeProp; + + public static final String SERIALIZED_NAME_ARRAY_NULLABLE_PROP = "array_nullable_prop"; + @SerializedName(SERIALIZED_NAME_ARRAY_NULLABLE_PROP) + @javax.annotation.Nullable + private List arrayNullableProp; + + public static final String SERIALIZED_NAME_ARRAY_AND_ITEMS_NULLABLE_PROP = "array_and_items_nullable_prop"; + @SerializedName(SERIALIZED_NAME_ARRAY_AND_ITEMS_NULLABLE_PROP) + @javax.annotation.Nullable + private List arrayAndItemsNullableProp; + + public static final String SERIALIZED_NAME_ARRAY_ITEMS_NULLABLE = "array_items_nullable"; + @SerializedName(SERIALIZED_NAME_ARRAY_ITEMS_NULLABLE) + @javax.annotation.Nullable + private List arrayItemsNullable = new ArrayList<>(); + + public static final String SERIALIZED_NAME_OBJECT_NULLABLE_PROP = "object_nullable_prop"; + @SerializedName(SERIALIZED_NAME_OBJECT_NULLABLE_PROP) + @javax.annotation.Nullable + private Map objectNullableProp; + + public static final String SERIALIZED_NAME_OBJECT_AND_ITEMS_NULLABLE_PROP = "object_and_items_nullable_prop"; + @SerializedName(SERIALIZED_NAME_OBJECT_AND_ITEMS_NULLABLE_PROP) + @javax.annotation.Nullable + private Map objectAndItemsNullableProp; + + public static final String SERIALIZED_NAME_OBJECT_ITEMS_NULLABLE = "object_items_nullable"; + @SerializedName(SERIALIZED_NAME_OBJECT_ITEMS_NULLABLE) + @javax.annotation.Nullable + private Map objectItemsNullable = new HashMap<>(); + + public NullableClass() { + } + + public NullableClass integerProp(@javax.annotation.Nullable Integer integerProp) { + this.integerProp = integerProp; + return this; + } + + /** + * Get integerProp + * @return integerProp + */ + @javax.annotation.Nullable + + public Integer getIntegerProp() { + return integerProp; + } + + public void setIntegerProp(@javax.annotation.Nullable Integer integerProp) { + this.integerProp = integerProp; + } + + + public NullableClass numberProp(@javax.annotation.Nullable BigDecimal numberProp) { + this.numberProp = numberProp; + return this; + } + + /** + * Get numberProp + * @return numberProp + */ + @javax.annotation.Nullable + + public BigDecimal getNumberProp() { + return numberProp; + } + + public void setNumberProp(@javax.annotation.Nullable BigDecimal numberProp) { + this.numberProp = numberProp; + } + + + public NullableClass booleanProp(@javax.annotation.Nullable Boolean booleanProp) { + this.booleanProp = booleanProp; + return this; + } + + /** + * Get booleanProp + * @return booleanProp + */ + @javax.annotation.Nullable + + public Boolean getBooleanProp() { + return booleanProp; + } + + public void setBooleanProp(@javax.annotation.Nullable Boolean booleanProp) { + this.booleanProp = booleanProp; + } + + + public NullableClass stringProp(@javax.annotation.Nullable String stringProp) { + this.stringProp = stringProp; + return this; + } + + /** + * Get stringProp + * @return stringProp + */ + @javax.annotation.Nullable + + public String getStringProp() { + return stringProp; + } + + public void setStringProp(@javax.annotation.Nullable String stringProp) { + this.stringProp = stringProp; + } + + + public NullableClass dateProp(@javax.annotation.Nullable LocalDate dateProp) { + this.dateProp = dateProp; + return this; + } + + /** + * Get dateProp + * @return dateProp + */ + @javax.annotation.Nullable + + public LocalDate getDateProp() { + return dateProp; + } + + public void setDateProp(@javax.annotation.Nullable LocalDate dateProp) { + this.dateProp = dateProp; + } + + + public NullableClass datetimeProp(@javax.annotation.Nullable OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + return this; + } + + /** + * Get datetimeProp + * @return datetimeProp + */ + @javax.annotation.Nullable + + public OffsetDateTime getDatetimeProp() { + return datetimeProp; + } + + public void setDatetimeProp(@javax.annotation.Nullable OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + } + + + public NullableClass arrayNullableProp(@javax.annotation.Nullable List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + return this; + } + + public NullableClass addArrayNullablePropItem(Object arrayNullablePropItem) { + if (this.arrayNullableProp == null) { + this.arrayNullableProp = new ArrayList<>(); + } + this.arrayNullableProp.add(arrayNullablePropItem); + return this; + } + + /** + * Get arrayNullableProp + * @return arrayNullableProp + */ + @javax.annotation.Nullable + + public List getArrayNullableProp() { + return arrayNullableProp; + } + + public void setArrayNullableProp(@javax.annotation.Nullable List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + } + + + public NullableClass arrayAndItemsNullableProp(@javax.annotation.Nullable List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + return this; + } + + public NullableClass addArrayAndItemsNullablePropItem(Object arrayAndItemsNullablePropItem) { + if (this.arrayAndItemsNullableProp == null) { + this.arrayAndItemsNullableProp = new ArrayList<>(); + } + this.arrayAndItemsNullableProp.add(arrayAndItemsNullablePropItem); + return this; + } + + /** + * Get arrayAndItemsNullableProp + * @return arrayAndItemsNullableProp + */ + @javax.annotation.Nullable + + public List getArrayAndItemsNullableProp() { + return arrayAndItemsNullableProp; + } + + public void setArrayAndItemsNullableProp(@javax.annotation.Nullable List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + } + + + public NullableClass arrayItemsNullable(@javax.annotation.Nullable List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + return this; + } + + public NullableClass addArrayItemsNullableItem(Object arrayItemsNullableItem) { + if (this.arrayItemsNullable == null) { + this.arrayItemsNullable = new ArrayList<>(); + } + this.arrayItemsNullable.add(arrayItemsNullableItem); + return this; + } + + /** + * Get arrayItemsNullable + * @return arrayItemsNullable + */ + @javax.annotation.Nullable + + public List getArrayItemsNullable() { + return arrayItemsNullable; + } + + public void setArrayItemsNullable(@javax.annotation.Nullable List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + } + + + public NullableClass objectNullableProp(@javax.annotation.Nullable Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + return this; + } + + public NullableClass putObjectNullablePropItem(String key, Object objectNullablePropItem) { + if (this.objectNullableProp == null) { + this.objectNullableProp = new HashMap<>(); + } + this.objectNullableProp.put(key, objectNullablePropItem); + return this; + } + + /** + * Get objectNullableProp + * @return objectNullableProp + */ + @javax.annotation.Nullable + + public Map getObjectNullableProp() { + return objectNullableProp; + } + + public void setObjectNullableProp(@javax.annotation.Nullable Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + } + + + public NullableClass objectAndItemsNullableProp(@javax.annotation.Nullable Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + return this; + } + + public NullableClass putObjectAndItemsNullablePropItem(String key, Object objectAndItemsNullablePropItem) { + if (this.objectAndItemsNullableProp == null) { + this.objectAndItemsNullableProp = new HashMap<>(); + } + this.objectAndItemsNullableProp.put(key, objectAndItemsNullablePropItem); + return this; + } + + /** + * Get objectAndItemsNullableProp + * @return objectAndItemsNullableProp + */ + @javax.annotation.Nullable + + public Map getObjectAndItemsNullableProp() { + return objectAndItemsNullableProp; + } + + public void setObjectAndItemsNullableProp(@javax.annotation.Nullable Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + } + + + public NullableClass objectItemsNullable(@javax.annotation.Nullable Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + return this; + } + + public NullableClass putObjectItemsNullableItem(String key, Object objectItemsNullableItem) { + if (this.objectItemsNullable == null) { + this.objectItemsNullable = new HashMap<>(); + } + this.objectItemsNullable.put(key, objectItemsNullableItem); + return this; + } + + /** + * Get objectItemsNullable + * @return objectItemsNullable + */ + @javax.annotation.Nullable + + public Map getObjectItemsNullable() { + return objectItemsNullable; + } + + public void setObjectItemsNullable(@javax.annotation.Nullable Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NullableClass instance itself + */ + public NullableClass putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NullableClass nullableClass = (NullableClass) o; + return Objects.equals(this.integerProp, nullableClass.integerProp) && + Objects.equals(this.numberProp, nullableClass.numberProp) && + Objects.equals(this.booleanProp, nullableClass.booleanProp) && + Objects.equals(this.stringProp, nullableClass.stringProp) && + Objects.equals(this.dateProp, nullableClass.dateProp) && + Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && + Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && + Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && + Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && + Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && + Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && + Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable)&& + Objects.equals(this.additionalProperties, nullableClass.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableClass {\n"); + sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); + sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); + sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); + sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); + sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); + sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); + sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); + sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); + sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); + sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); + sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); + sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable")); + + // 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 NullableClass + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NullableClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NullableClass is not found in the empty JSON string", NullableClass.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("string_prop") != null && !jsonObj.get("string_prop").isJsonNull()) && !jsonObj.get("string_prop").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `string_prop` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_prop").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("array_nullable_prop") != null && !jsonObj.get("array_nullable_prop").isJsonNull() && !jsonObj.get("array_nullable_prop").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_nullable_prop` to be an array in the JSON string but got `%s`", jsonObj.get("array_nullable_prop").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("array_and_items_nullable_prop") != null && !jsonObj.get("array_and_items_nullable_prop").isJsonNull() && !jsonObj.get("array_and_items_nullable_prop").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_and_items_nullable_prop` to be an array in the JSON string but got `%s`", jsonObj.get("array_and_items_nullable_prop").toString())); + } + // ensure the optional json data is an array if present + if (jsonObj.get("array_items_nullable") != null && !jsonObj.get("array_items_nullable").isJsonNull() && !jsonObj.get("array_items_nullable").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_items_nullable` to be an array in the JSON string but got `%s`", jsonObj.get("array_items_nullable").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NullableClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public NullableClass read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NullableClass instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NullableClass given an JSON string + * + * @param jsonString JSON string + * @return An instance of NullableClass + * @throws IOException if the JSON string is invalid with respect to NullableClass + */ + public static NullableClass fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NullableClass.class); + } + + /** + * Convert an instance of NullableClass to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableEnum.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableEnum.java new file mode 100644 index 000000000000..d28af0a9d1ea --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableEnum.java @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +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; + +/** + * Gets or Sets NullableEnum + */ +@JsonAdapter(NullableEnum.Adapter.class) +public enum NullableEnum { + + CUSTOM("custom"); + + private String value; + + NullableEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static NullableEnum fromValue(String value) { + for (NullableEnum b : NullableEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final NullableEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public NullableEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return NullableEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + NullableEnum.fromValue(value); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapError.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapError.java new file mode 100644 index 000000000000..bc1ba8e4f587 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapError.java @@ -0,0 +1,228 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Error response + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NullableFieldsMapError { + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nonnull + private String status; + + public static final String SERIALIZED_NAME_REASON = "reason"; + @SerializedName(SERIALIZED_NAME_REASON) + @javax.annotation.Nonnull + private String reason; + + public NullableFieldsMapError() { + } + + public NullableFieldsMapError status(@javax.annotation.Nonnull String status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @javax.annotation.Nonnull + + public String getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nonnull String status) { + this.status = status; + } + + + public NullableFieldsMapError reason(@javax.annotation.Nonnull String reason) { + this.reason = reason; + return this; + } + + /** + * Get reason + * @return reason + */ + @javax.annotation.Nonnull + + public String getReason() { + return reason; + } + + public void setReason(@javax.annotation.Nonnull String reason) { + this.reason = reason; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NullableFieldsMapError nullableFieldsMapError = (NullableFieldsMapError) o; + return Objects.equals(this.status, nullableFieldsMapError.status) && + Objects.equals(this.reason, nullableFieldsMapError.reason); + } + + @Override + public int hashCode() { + return Objects.hash(status, reason); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableFieldsMapError {\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" reason: ").append(toIndentedString(reason)).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) { + return o == null ? "null" : 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("status", "reason")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("status", "reason")); + } + + /** + * 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 NullableFieldsMapError + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NullableFieldsMapError.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NullableFieldsMapError is not found in the empty JSON string", NullableFieldsMapError.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!NullableFieldsMapError.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` in the JSON string is not defined in the `NullableFieldsMapError` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : NullableFieldsMapError.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + if (!jsonObj.get("reason").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `reason` to be a primitive type in the JSON string but got `%s`", jsonObj.get("reason").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableFieldsMapError.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableFieldsMapError' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NullableFieldsMapError.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableFieldsMapError value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public NullableFieldsMapError read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NullableFieldsMapError given an JSON string + * + * @param jsonString JSON string + * @return An instance of NullableFieldsMapError + * @throws IOException if the JSON string is invalid with respect to NullableFieldsMapError + */ + public static NullableFieldsMapError fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NullableFieldsMapError.class); + } + + /** + * Convert an instance of NullableFieldsMapError to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapResponse.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapResponse.java new file mode 100644 index 000000000000..35acc95bc680 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapResponse.java @@ -0,0 +1,368 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NullableFieldsMapResponse extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(NullableFieldsMapResponse.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NullableFieldsMapResponse instance itself + */ + public NullableFieldsMapResponse putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(NullableFieldsMapResponse instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched anyOf schema. + */ + private static void writeUnconsumedProperties(NullableFieldsMapResponse value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 NullableFieldsMapResponse + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + try { + // validate the JSON object to see if any exception is thrown + NullableFieldsMapSuccess.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for NullableFieldsMapSuccess failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + NullableFieldsMapError.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for NullableFieldsMapError failed with `%s`.", e.getMessage())); + } + + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for NullableFieldsMapResponse: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableFieldsMapResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableFieldsMapResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterNullableFieldsMapSuccess = gson.getDelegateAdapter(this, TypeToken.get(NullableFieldsMapSuccess.class)); + final TypeAdapter adapterNullableFieldsMapError = gson.getDelegateAdapter(this, TypeToken.get(NullableFieldsMapError.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableFieldsMapResponse value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `NullableFieldsMapSuccess` + if (value.getActualInstance() instanceof NullableFieldsMapSuccess) { + element = adapterNullableFieldsMapSuccess.toJsonTree((NullableFieldsMapSuccess)value.getActualInstance()); + } + // check if the actual instance is of the type `NullableFieldsMapError` + if (value.getActualInstance() instanceof NullableFieldsMapError) { + element = adapterNullableFieldsMapError.toJsonTree((NullableFieldsMapError)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: NullableFieldsMapError, NullableFieldsMapSuccess"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public NullableFieldsMapResponse read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize NullableFieldsMapSuccess + try { + // validate the JSON object to see if any exception is thrown + NullableFieldsMapSuccess.validateJsonElement(jsonElement); + NullableFieldsMapResponse ret = new NullableFieldsMapResponse(); + ret.setActualInstance(adapterNullableFieldsMapSuccess.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for NullableFieldsMapSuccess failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'NullableFieldsMapSuccess'", e); + } + + // deserialize NullableFieldsMapError + try { + // validate the JSON object to see if any exception is thrown + NullableFieldsMapError.validateJsonElement(jsonElement); + NullableFieldsMapResponse ret = new NullableFieldsMapResponse(); + ret.setActualInstance(adapterNullableFieldsMapError.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for NullableFieldsMapError failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'NullableFieldsMapError'", e); + } + + + throw new IOException(String.format("Failed deserialization for NullableFieldsMapResponse: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public NullableFieldsMapResponse() { + super("anyOf", Boolean.FALSE); + } + + public NullableFieldsMapResponse(NullableFieldsMapSuccess o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public NullableFieldsMapResponse(NullableFieldsMapError o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("NullableFieldsMapSuccess", NullableFieldsMapSuccess.class); + schemas.put("NullableFieldsMapError", NullableFieldsMapError.class); + } + + @Override + public Map> getSchemas() { + return NullableFieldsMapResponse.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * NullableFieldsMapError, NullableFieldsMapSuccess + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(NullableFieldsMapSuccess.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(NullableFieldsMapError.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be NullableFieldsMapError, NullableFieldsMapSuccess"); + } + + /** + * Get the actual instance, which can be the following: + * NullableFieldsMapError, NullableFieldsMapSuccess + * + * @return The actual instance (NullableFieldsMapError, NullableFieldsMapSuccess) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `NullableFieldsMapSuccess`. If the actual instance is not `NullableFieldsMapSuccess`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `NullableFieldsMapSuccess` + * @throws ClassCastException if the instance is not `NullableFieldsMapSuccess` + */ + @SuppressWarnings("unchecked") + public NullableFieldsMapSuccess getNullableFieldsMapSuccess() throws ClassCastException { + return (NullableFieldsMapSuccess)super.getActualInstance(); + } + + /** + * Get the actual instance of `NullableFieldsMapError`. If the actual instance is not `NullableFieldsMapError`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `NullableFieldsMapError` + * @throws ClassCastException if the instance is not `NullableFieldsMapError` + */ + @SuppressWarnings("unchecked") + public NullableFieldsMapError getNullableFieldsMapError() throws ClassCastException { + return (NullableFieldsMapError)super.getActualInstance(); + } + + + + /** + * Create an instance of NullableFieldsMapResponse given an JSON string + * + * @param jsonString JSON string + * @return An instance of NullableFieldsMapResponse + * @throws IOException if the JSON string is invalid with respect to NullableFieldsMapResponse + */ + public static NullableFieldsMapResponse fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NullableFieldsMapResponse.class); + } + + /** + * Convert an instance of NullableFieldsMapResponse to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapSuccess.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapSuccess.java new file mode 100644 index 000000000000..e0b4e3c9c937 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsMapSuccess.java @@ -0,0 +1,234 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Success response containing a map of objects with nullable fields + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NullableFieldsMapSuccess { + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nonnull + private String status; + + public static final String SERIALIZED_NAME_POSITIONS = "positions"; + @SerializedName(SERIALIZED_NAME_POSITIONS) + @javax.annotation.Nonnull + private Map positions; + + public NullableFieldsMapSuccess() { + } + + public NullableFieldsMapSuccess status(@javax.annotation.Nonnull String status) { + this.status = status; + return this; + } + + /** + * Get status + * @return status + */ + @javax.annotation.Nonnull + + public String getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nonnull String status) { + this.status = status; + } + + + public NullableFieldsMapSuccess positions(@javax.annotation.Nonnull Map positions) { + this.positions = positions; + return this; + } + + public NullableFieldsMapSuccess putPositionsItem(String key, NullableFieldsValue positionsItem) { + if (this.positions == null) { + this.positions = new HashMap<>(); + } + this.positions.put(key, positionsItem); + return this; + } + + /** + * Get positions + * @return positions + */ + @javax.annotation.Nonnull + + public Map getPositions() { + return positions; + } + + public void setPositions(@javax.annotation.Nonnull Map positions) { + this.positions = positions; + } + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NullableFieldsMapSuccess nullableFieldsMapSuccess = (NullableFieldsMapSuccess) o; + return Objects.equals(this.status, nullableFieldsMapSuccess.status) && + Objects.equals(this.positions, nullableFieldsMapSuccess.positions); + } + + @Override + public int hashCode() { + return Objects.hash(status, positions); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableFieldsMapSuccess {\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" positions: ").append(toIndentedString(positions)).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) { + return o == null ? "null" : 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("status", "positions")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("status", "positions")); + } + + /** + * 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 NullableFieldsMapSuccess + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NullableFieldsMapSuccess.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NullableFieldsMapSuccess is not found in the empty JSON string", NullableFieldsMapSuccess.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + Set> entries = jsonElement.getAsJsonObject().entrySet(); + // check to see if the JSON string contains additional fields + for (Map.Entry entry : entries) { + if (!NullableFieldsMapSuccess.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` in the JSON string is not defined in the `NullableFieldsMapSuccess` properties. JSON: %s", entry.getKey(), jsonElement.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : NullableFieldsMapSuccess.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableFieldsMapSuccess.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableFieldsMapSuccess' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NullableFieldsMapSuccess.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableFieldsMapSuccess value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public NullableFieldsMapSuccess read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + return thisAdapter.fromJsonTree(jsonElement); + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NullableFieldsMapSuccess given an JSON string + * + * @param jsonString JSON string + * @return An instance of NullableFieldsMapSuccess + * @throws IOException if the JSON string is invalid with respect to NullableFieldsMapSuccess + */ + public static NullableFieldsMapSuccess fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NullableFieldsMapSuccess.class); + } + + /** + * Convert an instance of NullableFieldsMapSuccess to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsValue.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsValue.java new file mode 100644 index 000000000000..9d40385d6ac8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableFieldsValue.java @@ -0,0 +1,313 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Object with required but nullable string fields + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NullableFieldsValue { + public static final String SERIALIZED_NAME_BEFORE = "before"; + @SerializedName(SERIALIZED_NAME_BEFORE) + @javax.annotation.Nullable + private String before; + + public static final String SERIALIZED_NAME_AFTER = "after"; + @SerializedName(SERIALIZED_NAME_AFTER) + @javax.annotation.Nullable + private String after; + + public NullableFieldsValue() { + } + + public NullableFieldsValue before(@javax.annotation.Nullable String before) { + this.before = before; + return this; + } + + /** + * Get before + * @return before + */ + @javax.annotation.Nullable + + public String getBefore() { + return before; + } + + public void setBefore(@javax.annotation.Nullable String before) { + this.before = before; + } + + + public NullableFieldsValue after(@javax.annotation.Nullable String after) { + this.after = after; + return this; + } + + /** + * Get after + * @return after + */ + @javax.annotation.Nullable + + public String getAfter() { + return after; + } + + public void setAfter(@javax.annotation.Nullable String after) { + this.after = after; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NullableFieldsValue instance itself + */ + public NullableFieldsValue putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NullableFieldsValue nullableFieldsValue = (NullableFieldsValue) o; + return Objects.equals(this.before, nullableFieldsValue.before) && + Objects.equals(this.after, nullableFieldsValue.after)&& + Objects.equals(this.additionalProperties, nullableFieldsValue.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(before, after, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableFieldsValue {\n"); + sb.append(" before: ").append(toIndentedString(before)).append("\n"); + sb.append(" after: ").append(toIndentedString(after)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("before", "after")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("before", "after")); + } + + /** + * 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 NullableFieldsValue + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NullableFieldsValue.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NullableFieldsValue is not found in the empty JSON string", NullableFieldsValue.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : NullableFieldsValue.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("before") != null && !jsonObj.get("before").isJsonNull()) && !jsonObj.get("before").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `before` to be a primitive type in the JSON string but got `%s`", jsonObj.get("before").toString())); + } + if ((jsonObj.get("after") != null && !jsonObj.get("after").isJsonNull()) && !jsonObj.get("after").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `after` to be a primitive type in the JSON string but got `%s`", jsonObj.get("after").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableFieldsValue.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableFieldsValue' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NullableFieldsValue.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableFieldsValue value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public NullableFieldsValue read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NullableFieldsValue instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NullableFieldsValue given an JSON string + * + * @param jsonString JSON string + * @return An instance of NullableFieldsValue + * @throws IOException if the JSON string is invalid with respect to NullableFieldsValue + */ + public static NullableFieldsValue fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NullableFieldsValue.class); + } + + /** + * Convert an instance of NullableFieldsValue to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableShape.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableShape.java new file mode 100644 index 000000000000..56e503f30f6d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NullableShape.java @@ -0,0 +1,411 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NullableShape extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(NullableShape.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NullableShape instance itself + */ + public NullableShape putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(NullableShape instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(NullableShape value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 NullableShape + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("shapeType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'shapeType' is missing."); + } + String discriminatorValue = jsonObject.get("shapeType").getAsString(); + if ("Quadrilateral".equals(discriminatorValue)) { + Quadrilateral.validateJsonElement(jsonElement); + return; + } + if ("Triangle".equals(discriminatorValue)) { + Triangle.validateJsonElement(jsonElement); + return; + } + // deserialize Triangle + try { + // validate the JSON object to see if any exception is thrown + Triangle.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage())); + } + + // deserialize Quadrilateral + try { + // validate the JSON object to see if any exception is thrown + Quadrilateral.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for NullableShape: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableShape.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableShape' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class)); + final TypeAdapter adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableShape value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Triangle` + if (value.getActualInstance() instanceof Triangle) { + element = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()); + } + // check if the actual instance is of the type `Quadrilateral` + if (value.getActualInstance() instanceof Quadrilateral) { + element = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public NullableShape read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("shapeType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'shapeType' is missing."); + } + String discriminatorValue = jsonObject.get("shapeType").getAsString(); + if ("Quadrilateral".equals(discriminatorValue)) { + deserialized = adapterQuadrilateral.fromJsonTree(jsonElement); + NullableShape ret = new NullableShape(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("Triangle".equals(discriminatorValue)) { + deserialized = adapterTriangle.fromJsonTree(jsonElement); + NullableShape ret = new NullableShape(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Triangle + try { + // validate the JSON object to see if any exception is thrown + Triangle.validateJsonElement(jsonElement); + actualAdapter = adapterTriangle; + match++; + log.log(Level.FINER, "Input data matches schema 'Triangle'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); + } + + // deserialize Quadrilateral + try { + // validate the JSON object to see if any exception is thrown + Quadrilateral.validateJsonElement(jsonElement); + actualAdapter = adapterQuadrilateral; + match++; + log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); + } + + if (match == 1) { + NullableShape ret = new NullableShape(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for NullableShape: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public NullableShape() { + super("oneOf", Boolean.TRUE); + } + + public NullableShape(Triangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public NullableShape(Quadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Triangle", Triangle.class); + schemas.put("Quadrilateral", Quadrilateral.class); + } + + @Override + public Map> getSchemas() { + return NullableShape.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Quadrilateral, Triangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Triangle.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Quadrilateral.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); + } + + /** + * Get the actual instance, which can be the following: + * Quadrilateral, Triangle + * + * @return The actual instance (Quadrilateral, Triangle) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Triangle` + * @throws ClassCastException if the instance is not `Triangle` + */ + @SuppressWarnings("unchecked") + public Triangle getTriangle() throws ClassCastException { + return (Triangle)super.getActualInstance(); + } + + /** + * Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Quadrilateral` + * @throws ClassCastException if the instance is not `Quadrilateral` + */ + @SuppressWarnings("unchecked") + public Quadrilateral getQuadrilateral() throws ClassCastException { + return (Quadrilateral)super.getActualInstance(); + } + + + + /** + * Create an instance of NullableShape given an JSON string + * + * @param jsonString JSON string + * @return An instance of NullableShape + * @throws IOException if the JSON string is invalid with respect to NullableShape + */ + public static NullableShape fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NullableShape.class); + } + + /** + * Convert an instance of NullableShape to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NumberOnly.java new file mode 100644 index 000000000000..52bfb347efa8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -0,0 +1,274 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * NumberOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class NumberOnly { + public static final String SERIALIZED_NAME_JUST_NUMBER = "JustNumber"; + @SerializedName(SERIALIZED_NAME_JUST_NUMBER) + @javax.annotation.Nullable + private BigDecimal justNumber; + + public NumberOnly() { + } + + public NumberOnly justNumber(@javax.annotation.Nullable BigDecimal justNumber) { + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + */ + @javax.annotation.Nullable + + public BigDecimal getJustNumber() { + return justNumber; + } + + public void setJustNumber(@javax.annotation.Nullable BigDecimal justNumber) { + this.justNumber = justNumber; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the NumberOnly instance itself + */ + public NumberOnly putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber)&& + Objects.equals(this.additionalProperties, numberOnly.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("JustNumber")); + + // 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 NumberOnly + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!NumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in NumberOnly is not found in the empty JSON string", NumberOnly.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NumberOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NumberOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NumberOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NumberOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public NumberOnly read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + NumberOnly instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of NumberOnly given an JSON string + * + * @param jsonString JSON string + * @return An instance of NumberOnly + * @throws IOException if the JSON string is invalid with respect to NumberOnly + */ + public static NumberOnly fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, NumberOnly.class); + } + + /** + * Convert an instance of NumberOnly to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java new file mode 100644 index 000000000000..c96ccde9be5b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -0,0 +1,390 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ObjectWithDeprecatedFields + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ObjectWithDeprecatedFields { + public static final String SERIALIZED_NAME_UUID = "uuid"; + @SerializedName(SERIALIZED_NAME_UUID) + @javax.annotation.Nullable + private String uuid; + + public static final String SERIALIZED_NAME_ID = "id"; + @Deprecated + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private BigDecimal id; + + public static final String SERIALIZED_NAME_DEPRECATED_REF = "deprecatedRef"; + @Deprecated + @SerializedName(SERIALIZED_NAME_DEPRECATED_REF) + @javax.annotation.Nullable + private DeprecatedObject deprecatedRef; + + public static final String SERIALIZED_NAME_BARS = "bars"; + @Deprecated + @SerializedName(SERIALIZED_NAME_BARS) + @javax.annotation.Nullable + private List bars = new ArrayList<>(); + + public ObjectWithDeprecatedFields() { + } + + public ObjectWithDeprecatedFields uuid(@javax.annotation.Nullable String uuid) { + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + */ + @javax.annotation.Nullable + + public String getUuid() { + return uuid; + } + + public void setUuid(@javax.annotation.Nullable String uuid) { + this.uuid = uuid; + } + + + @Deprecated + public ObjectWithDeprecatedFields id(@javax.annotation.Nullable BigDecimal id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + * @deprecated + */ + @Deprecated + @javax.annotation.Nullable + + public BigDecimal getId() { + return id; + } + + @Deprecated + public void setId(@javax.annotation.Nullable BigDecimal id) { + this.id = id; + } + + + @Deprecated + public ObjectWithDeprecatedFields deprecatedRef(@javax.annotation.Nullable DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + return this; + } + + /** + * Get deprecatedRef + * @return deprecatedRef + * @deprecated + */ + @Deprecated + @javax.annotation.Nullable + + public DeprecatedObject getDeprecatedRef() { + return deprecatedRef; + } + + @Deprecated + public void setDeprecatedRef(@javax.annotation.Nullable DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + } + + + @Deprecated + public ObjectWithDeprecatedFields bars(@javax.annotation.Nullable List bars) { + this.bars = bars; + return this; + } + + public ObjectWithDeprecatedFields addBarsItem(String barsItem) { + if (this.bars == null) { + this.bars = new ArrayList<>(); + } + this.bars.add(barsItem); + return this; + } + + /** + * Get bars + * @return bars + * @deprecated + */ + @Deprecated + @javax.annotation.Nullable + + public List getBars() { + return bars; + } + + @Deprecated + public void setBars(@javax.annotation.Nullable List bars) { + this.bars = bars; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ObjectWithDeprecatedFields instance itself + */ + public ObjectWithDeprecatedFields putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ObjectWithDeprecatedFields objectWithDeprecatedFields = (ObjectWithDeprecatedFields) o; + return Objects.equals(this.uuid, objectWithDeprecatedFields.uuid) && + Objects.equals(this.id, objectWithDeprecatedFields.id) && + Objects.equals(this.deprecatedRef, objectWithDeprecatedFields.deprecatedRef) && + Objects.equals(this.bars, objectWithDeprecatedFields.bars)&& + Objects.equals(this.additionalProperties, objectWithDeprecatedFields.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, id, deprecatedRef, bars, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ObjectWithDeprecatedFields {\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" deprecatedRef: ").append(toIndentedString(deprecatedRef)).append("\n"); + sb.append(" bars: ").append(toIndentedString(bars)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("uuid", "id", "deprecatedRef", "bars")); + + // 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 ObjectWithDeprecatedFields + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ObjectWithDeprecatedFields.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ObjectWithDeprecatedFields is not found in the empty JSON string", ObjectWithDeprecatedFields.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString())); + } + // validate the optional field `deprecatedRef` + if (jsonObj.get("deprecatedRef") != null && !jsonObj.get("deprecatedRef").isJsonNull()) { + DeprecatedObject.validateJsonElement(jsonObj.get("deprecatedRef")); + } + // ensure the optional json data is an array if present + if (jsonObj.get("bars") != null && !jsonObj.get("bars").isJsonNull() && !jsonObj.get("bars").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `bars` to be an array in the JSON string but got `%s`", jsonObj.get("bars").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ObjectWithDeprecatedFields.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ObjectWithDeprecatedFields' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ObjectWithDeprecatedFields.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ObjectWithDeprecatedFields value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ObjectWithDeprecatedFields read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ObjectWithDeprecatedFields instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ObjectWithDeprecatedFields given an JSON string + * + * @param jsonString JSON string + * @return An instance of ObjectWithDeprecatedFields + * @throws IOException if the JSON string is invalid with respect to ObjectWithDeprecatedFields + */ + public static ObjectWithDeprecatedFields fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ObjectWithDeprecatedFields.class); + } + + /** + * Convert an instance of ObjectWithDeprecatedFields to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Order.java new file mode 100644 index 000000000000..d6c4b1850695 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Order.java @@ -0,0 +1,471 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.time.OffsetDateTime; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Order + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Order { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_PET_ID = "petId"; + @SerializedName(SERIALIZED_NAME_PET_ID) + @javax.annotation.Nullable + private Long petId; + + public static final String SERIALIZED_NAME_QUANTITY = "quantity"; + @SerializedName(SERIALIZED_NAME_QUANTITY) + @javax.annotation.Nullable + private Integer quantity; + + public static final String SERIALIZED_NAME_SHIP_DATE = "shipDate"; + @SerializedName(SERIALIZED_NAME_SHIP_DATE) + @javax.annotation.Nullable + private OffsetDateTime shipDate; + + /** + * Order Status + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public static final String SERIALIZED_NAME_COMPLETE = "complete"; + @SerializedName(SERIALIZED_NAME_COMPLETE) + @javax.annotation.Nullable + private Boolean complete = false; + + public Order() { + } + + public Order id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Order petId(@javax.annotation.Nullable Long petId) { + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + */ + @javax.annotation.Nullable + + public Long getPetId() { + return petId; + } + + public void setPetId(@javax.annotation.Nullable Long petId) { + this.petId = petId; + } + + + public Order quantity(@javax.annotation.Nullable Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + */ + @javax.annotation.Nullable + + public Integer getQuantity() { + return quantity; + } + + public void setQuantity(@javax.annotation.Nullable Integer quantity) { + this.quantity = quantity; + } + + + public Order shipDate(@javax.annotation.Nullable OffsetDateTime shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + */ + @javax.annotation.Nullable + + public OffsetDateTime getShipDate() { + return shipDate; + } + + public void setShipDate(@javax.annotation.Nullable OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + + public Order status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * Order Status + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + + public Order complete(@javax.annotation.Nullable Boolean complete) { + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + */ + @javax.annotation.Nullable + + public Boolean getComplete() { + return complete; + } + + public void setComplete(@javax.annotation.Nullable Boolean complete) { + this.complete = complete; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Order instance itself + */ + public Order putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete)&& + Objects.equals(this.additionalProperties, order.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "petId", "quantity", "shipDate", "status", "complete")); + + // 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 Order + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Order.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Order' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Order.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Order value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Order read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Order instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Order given an JSON string + * + * @param jsonString JSON string + * @return An instance of Order + * @throws IOException if the JSON string is invalid with respect to Order + */ + public static Order fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Order.class); + } + + /** + * Convert an instance of Order to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterComposite.java new file mode 100644 index 000000000000..3d039aae2aee --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -0,0 +1,331 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * OuterComposite + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class OuterComposite { + public static final String SERIALIZED_NAME_MY_NUMBER = "my_number"; + @SerializedName(SERIALIZED_NAME_MY_NUMBER) + @javax.annotation.Nullable + private BigDecimal myNumber; + + public static final String SERIALIZED_NAME_MY_STRING = "my_string"; + @SerializedName(SERIALIZED_NAME_MY_STRING) + @javax.annotation.Nullable + private String myString; + + public static final String SERIALIZED_NAME_MY_BOOLEAN = "my_boolean"; + @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) + @javax.annotation.Nullable + private Boolean myBoolean; + + public OuterComposite() { + } + + public OuterComposite myNumber(@javax.annotation.Nullable BigDecimal myNumber) { + this.myNumber = myNumber; + return this; + } + + /** + * Get myNumber + * @return myNumber + */ + @javax.annotation.Nullable + + public BigDecimal getMyNumber() { + return myNumber; + } + + public void setMyNumber(@javax.annotation.Nullable BigDecimal myNumber) { + this.myNumber = myNumber; + } + + + public OuterComposite myString(@javax.annotation.Nullable String myString) { + this.myString = myString; + return this; + } + + /** + * Get myString + * @return myString + */ + @javax.annotation.Nullable + + public String getMyString() { + return myString; + } + + public void setMyString(@javax.annotation.Nullable String myString) { + this.myString = myString; + } + + + public OuterComposite myBoolean(@javax.annotation.Nullable Boolean myBoolean) { + this.myBoolean = myBoolean; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + */ + @javax.annotation.Nullable + + public Boolean getMyBoolean() { + return myBoolean; + } + + public void setMyBoolean(@javax.annotation.Nullable Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the OuterComposite instance itself + */ + public OuterComposite putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OuterComposite outerComposite = (OuterComposite) o; + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean)&& + Objects.equals(this.additionalProperties, outerComposite.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(myNumber, myString, myBoolean, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("my_number", "my_string", "my_boolean")); + + // 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 OuterComposite + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!OuterComposite.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in OuterComposite is not found in the empty JSON string", OuterComposite.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonNull()) && !jsonObj.get("my_string").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `my_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("my_string").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!OuterComposite.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'OuterComposite' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(OuterComposite.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, OuterComposite value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public OuterComposite read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + OuterComposite instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of OuterComposite given an JSON string + * + * @param jsonString JSON string + * @return An instance of OuterComposite + * @throws IOException if the JSON string is invalid with respect to OuterComposite + */ + public static OuterComposite fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, OuterComposite.class); + } + + /** + * Convert an instance of OuterComposite to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnum.java new file mode 100644 index 000000000000..849bfbf89285 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -0,0 +1,84 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +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; + +/** + * Gets or Sets OuterEnum + */ +@JsonAdapter(OuterEnum.Adapter.class) +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"), + + LOWER_CASE_S("s"), + + UPPER_CASE_S("S"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnum fromValue(String value) { + for (OuterEnum b : OuterEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return OuterEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + OuterEnum.fromValue(value); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java new file mode 100644 index 000000000000..09897c14f170 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +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; + +/** + * Gets or Sets OuterEnumDefaultValue + */ +@JsonAdapter(OuterEnumDefaultValue.Adapter.class) +public enum OuterEnumDefaultValue { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnumDefaultValue(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnumDefaultValue fromValue(String value) { + for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnumDefaultValue enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnumDefaultValue read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return OuterEnumDefaultValue.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + OuterEnumDefaultValue.fromValue(value); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumInteger.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumInteger.java new file mode 100644 index 000000000000..baab420fb37b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumInteger.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +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; + +/** + * Gets or Sets OuterEnumInteger + */ +@Deprecated +@JsonAdapter(OuterEnumInteger.Adapter.class) +public enum OuterEnumInteger { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumInteger(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnumInteger fromValue(Integer value) { + for (OuterEnumInteger b : OuterEnumInteger.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnumInteger enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnumInteger read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return OuterEnumInteger.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + OuterEnumInteger.fromValue(value); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java new file mode 100644 index 000000000000..8d5372492bed --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +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; + +/** + * Gets or Sets OuterEnumIntegerDefaultValue + */ +@JsonAdapter(OuterEnumIntegerDefaultValue.Adapter.class) +public enum OuterEnumIntegerDefaultValue { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumIntegerDefaultValue(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnumIntegerDefaultValue fromValue(Integer value) { + for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnumIntegerDefaultValue enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnumIntegerDefaultValue read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return OuterEnumIntegerDefaultValue.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + OuterEnumIntegerDefaultValue.fromValue(value); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ParentPet.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ParentPet.java new file mode 100644 index 000000000000..120675af9844 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ParentPet.java @@ -0,0 +1,222 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ParentPet + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ParentPet extends GrandparentAnimal { + public ParentPet() { + this.petType = this.getClass().getSimpleName(); + } + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * The bag is inherited from the superclass. + * + * @param key name of the property + * @param value value of the property + * @return the ParentPet instance itself + */ + @Override + public ParentPet putAdditionalProperty(String key, Object value) { + super.putAdditionalProperty(key, value); + return this; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ParentPet {\n"); + sb.append(" ").append(toIndentedString(super.toString())).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) { + return o == null ? "null" : 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("pet_type")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("pet_type")); + } + + /** + * 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 ParentPet + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ParentPet.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ParentPet is not found in the empty JSON string", ParentPet.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ParentPet.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ParentPet.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ParentPet' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ParentPet.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ParentPet value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ParentPet read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ParentPet instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ParentPet given an JSON string + * + * @param jsonString JSON string + * @return An instance of ParentPet + * @throws IOException if the JSON string is invalid with respect to ParentPet + */ + public static ParentPet fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ParentPet.class); + } + + /** + * Convert an instance of ParentPet to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 000000000000..fbf65c542a70 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,521 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Pet + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Pet { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + @javax.annotation.Nullable + private Category category; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + @javax.annotation.Nonnull + private List photoUrls = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + @javax.annotation.Nullable + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public Pet() { + } + + public Pet id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Pet category(@javax.annotation.Nullable Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @javax.annotation.Nullable + + public Category getCategory() { + return category; + } + + public void setCategory(@javax.annotation.Nullable Category category) { + this.category = category; + } + + + public Pet name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public Pet photoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @javax.annotation.Nonnull + + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(@javax.annotation.Nullable List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @javax.annotation.Nullable + + public List getTags() { + return tags; + } + + public void setTags(@javax.annotation.Nullable List tags) { + this.tags = tags; + } + + + public Pet status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Pet instance itself + */ + public Pet putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status)&& + Objects.equals(this.additionalProperties, pet.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "category", "name", "photoUrls", "tags", "status")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "photoUrls")); + } + + /** + * 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 Pet + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Pet.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `category` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category")); + } + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // ensure the required json array is present + if (jsonObj.get("photoUrls") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("photoUrls").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); + } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + com.google.gson.JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + }; + } + } + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Pet.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Pet' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Pet.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Pet value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Pet read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Pet instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Pet given an JSON string + * + * @param jsonString JSON string + * @return An instance of Pet + * @throws IOException if the JSON string is invalid with respect to Pet + */ + public static Pet fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Pet.class); + } + + /** + * Convert an instance of Pet to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetComposition.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetComposition.java new file mode 100644 index 000000000000..94febbd6fd1d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetComposition.java @@ -0,0 +1,521 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * PetComposition + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class PetComposition { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + @javax.annotation.Nullable + private Category category; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + @javax.annotation.Nonnull + private List photoUrls = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + @javax.annotation.Nullable + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public PetComposition() { + } + + public PetComposition id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public PetComposition category(@javax.annotation.Nullable Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @javax.annotation.Nullable + + public Category getCategory() { + return category; + } + + public void setCategory(@javax.annotation.Nullable Category category) { + this.category = category; + } + + + public PetComposition name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public PetComposition photoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public PetComposition addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @javax.annotation.Nonnull + + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + } + + + public PetComposition tags(@javax.annotation.Nullable List tags) { + this.tags = tags; + return this; + } + + public PetComposition addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @javax.annotation.Nullable + + public List getTags() { + return tags; + } + + public void setTags(@javax.annotation.Nullable List tags) { + this.tags = tags; + } + + + public PetComposition status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the PetComposition instance itself + */ + public PetComposition putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PetComposition petComposition = (PetComposition) o; + return Objects.equals(this.id, petComposition.id) && + Objects.equals(this.category, petComposition.category) && + Objects.equals(this.name, petComposition.name) && + Objects.equals(this.photoUrls, petComposition.photoUrls) && + Objects.equals(this.tags, petComposition.tags) && + Objects.equals(this.status, petComposition.status)&& + Objects.equals(this.additionalProperties, petComposition.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PetComposition {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "category", "name", "photoUrls", "tags", "status")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "photoUrls")); + } + + /** + * 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 PetComposition + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!PetComposition.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in PetComposition is not found in the empty JSON string", PetComposition.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : PetComposition.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `category` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category")); + } + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // ensure the required json array is present + if (jsonObj.get("photoUrls") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("photoUrls").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); + } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + com.google.gson.JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + }; + } + } + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!PetComposition.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'PetComposition' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(PetComposition.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, PetComposition value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public PetComposition read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + PetComposition instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of PetComposition given an JSON string + * + * @param jsonString JSON string + * @return An instance of PetComposition + * @throws IOException if the JSON string is invalid with respect to PetComposition + */ + public static PetComposition fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, PetComposition.class); + } + + /** + * Convert an instance of PetComposition to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetRef.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetRef.java new file mode 100644 index 000000000000..ca588c4c054a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetRef.java @@ -0,0 +1,521 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * PetRef + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class PetRef { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + @javax.annotation.Nullable + private Category category; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + @javax.annotation.Nonnull + private List photoUrls = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + @javax.annotation.Nullable + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public PetRef() { + } + + public PetRef id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public PetRef category(@javax.annotation.Nullable Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @javax.annotation.Nullable + + public Category getCategory() { + return category; + } + + public void setCategory(@javax.annotation.Nullable Category category) { + this.category = category; + } + + + public PetRef name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public PetRef photoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public PetRef addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @javax.annotation.Nonnull + + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + } + + + public PetRef tags(@javax.annotation.Nullable List tags) { + this.tags = tags; + return this; + } + + public PetRef addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @javax.annotation.Nullable + + public List getTags() { + return tags; + } + + public void setTags(@javax.annotation.Nullable List tags) { + this.tags = tags; + } + + + public PetRef status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the PetRef instance itself + */ + public PetRef putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PetRef petRef = (PetRef) o; + return Objects.equals(this.id, petRef.id) && + Objects.equals(this.category, petRef.category) && + Objects.equals(this.name, petRef.name) && + Objects.equals(this.photoUrls, petRef.photoUrls) && + Objects.equals(this.tags, petRef.tags) && + Objects.equals(this.status, petRef.status)&& + Objects.equals(this.additionalProperties, petRef.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PetRef {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "category", "name", "photoUrls", "tags", "status")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "photoUrls")); + } + + /** + * 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 PetRef + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!PetRef.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in PetRef is not found in the empty JSON string", PetRef.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : PetRef.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `category` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category")); + } + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // ensure the required json array is present + if (jsonObj.get("photoUrls") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("photoUrls").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); + } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + com.google.gson.JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + }; + } + } + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!PetRef.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'PetRef' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(PetRef.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, PetRef value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public PetRef read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + PetRef instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of PetRef given an JSON string + * + * @param jsonString JSON string + * @return An instance of PetRef + * @throws IOException if the JSON string is invalid with respect to PetRef + */ + public static PetRef fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, PetRef.class); + } + + /** + * Convert an instance of PetRef to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetUsingAllOf.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetUsingAllOf.java new file mode 100644 index 000000000000..87b389477bbd --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetUsingAllOf.java @@ -0,0 +1,521 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * PetUsingAllOf + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class PetUsingAllOf { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + @javax.annotation.Nullable + private Category category; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + @javax.annotation.Nonnull + private List photoUrls = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + @javax.annotation.Nullable + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public PetUsingAllOf() { + } + + public PetUsingAllOf id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public PetUsingAllOf category(@javax.annotation.Nullable Category category) { + this.category = category; + return this; + } + + /** + * multi line description 2nd line last line + * @return category + */ + @javax.annotation.Nullable + + public Category getCategory() { + return category; + } + + public void setCategory(@javax.annotation.Nullable Category category) { + this.category = category; + } + + + public PetUsingAllOf name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public PetUsingAllOf photoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public PetUsingAllOf addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @javax.annotation.Nonnull + + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + } + + + public PetUsingAllOf tags(@javax.annotation.Nullable List tags) { + this.tags = tags; + return this; + } + + public PetUsingAllOf addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @javax.annotation.Nullable + + public List getTags() { + return tags; + } + + public void setTags(@javax.annotation.Nullable List tags) { + this.tags = tags; + } + + + public PetUsingAllOf status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the PetUsingAllOf instance itself + */ + public PetUsingAllOf putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PetUsingAllOf petUsingAllOf = (PetUsingAllOf) o; + return Objects.equals(this.id, petUsingAllOf.id) && + Objects.equals(this.category, petUsingAllOf.category) && + Objects.equals(this.name, petUsingAllOf.name) && + Objects.equals(this.photoUrls, petUsingAllOf.photoUrls) && + Objects.equals(this.tags, petUsingAllOf.tags) && + Objects.equals(this.status, petUsingAllOf.status)&& + Objects.equals(this.additionalProperties, petUsingAllOf.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PetUsingAllOf {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "category", "name", "photoUrls", "tags", "status")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "photoUrls")); + } + + /** + * 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 PetUsingAllOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!PetUsingAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in PetUsingAllOf is not found in the empty JSON string", PetUsingAllOf.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : PetUsingAllOf.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `category` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category")); + } + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // ensure the required json array is present + if (jsonObj.get("photoUrls") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("photoUrls").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); + } + if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) { + com.google.gson.JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + if (jsonArraytags != null) { + // ensure the json data is an array + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + + // validate the optional field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + }; + } + } + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!PetUsingAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'PetUsingAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(PetUsingAllOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, PetUsingAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public PetUsingAllOf read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + PetUsingAllOf instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of PetUsingAllOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of PetUsingAllOf + * @throws IOException if the JSON string is invalid with respect to PetUsingAllOf + */ + public static PetUsingAllOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, PetUsingAllOf.class); + } + + /** + * Convert an instance of PetUsingAllOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java new file mode 100644 index 000000000000..2c87a8e3a3bc --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java @@ -0,0 +1,517 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * PetWithRequiredTags + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class PetWithRequiredTags { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + @javax.annotation.Nullable + private Category category; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + @javax.annotation.Nonnull + private List photoUrls = new ArrayList<>(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + @javax.annotation.Nonnull + private List tags = new ArrayList<>(); + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + @javax.annotation.Nullable + private StatusEnum status; + + public PetWithRequiredTags() { + } + + public PetWithRequiredTags id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public PetWithRequiredTags category(@javax.annotation.Nullable Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @javax.annotation.Nullable + + public Category getCategory() { + return category; + } + + public void setCategory(@javax.annotation.Nullable Category category) { + this.category = category; + } + + + public PetWithRequiredTags name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public PetWithRequiredTags photoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public PetWithRequiredTags addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @javax.annotation.Nonnull + + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(@javax.annotation.Nonnull List photoUrls) { + this.photoUrls = photoUrls; + } + + + public PetWithRequiredTags tags(@javax.annotation.Nonnull List tags) { + this.tags = tags; + return this; + } + + public PetWithRequiredTags addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @javax.annotation.Nonnull + + public List getTags() { + return tags; + } + + public void setTags(@javax.annotation.Nonnull List tags) { + this.tags = tags; + } + + + public PetWithRequiredTags status(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + */ + @javax.annotation.Nullable + + public StatusEnum getStatus() { + return status; + } + + public void setStatus(@javax.annotation.Nullable StatusEnum status) { + this.status = status; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the PetWithRequiredTags instance itself + */ + public PetWithRequiredTags putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PetWithRequiredTags petWithRequiredTags = (PetWithRequiredTags) o; + return Objects.equals(this.id, petWithRequiredTags.id) && + Objects.equals(this.category, petWithRequiredTags.category) && + Objects.equals(this.name, petWithRequiredTags.name) && + Objects.equals(this.photoUrls, petWithRequiredTags.photoUrls) && + Objects.equals(this.tags, petWithRequiredTags.tags) && + Objects.equals(this.status, petWithRequiredTags.status)&& + Objects.equals(this.additionalProperties, petWithRequiredTags.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PetWithRequiredTags {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "category", "name", "photoUrls", "tags", "status")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "photoUrls", "tags")); + } + + /** + * 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 PetWithRequiredTags + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!PetWithRequiredTags.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in PetWithRequiredTags is not found in the empty JSON string", PetWithRequiredTags.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : PetWithRequiredTags.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `category` + if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) { + Category.validateJsonElement(jsonObj.get("category")); + } + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // ensure the required json array is present + if (jsonObj.get("photoUrls") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("photoUrls").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString())); + } + if (jsonObj.get("tags") != null) { + if (!jsonObj.get("tags").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `tags` to be an array in the JSON string but got `%s`", jsonObj.get("tags").toString())); + } + com.google.gson.JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + // validate the required field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + } + } + if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); + } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!PetWithRequiredTags.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'PetWithRequiredTags' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(PetWithRequiredTags.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, PetWithRequiredTags value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public PetWithRequiredTags read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + PetWithRequiredTags instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of PetWithRequiredTags given an JSON string + * + * @param jsonString JSON string + * @return An instance of PetWithRequiredTags + * @throws IOException if the JSON string is invalid with respect to PetWithRequiredTags + */ + public static PetWithRequiredTags fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, PetWithRequiredTags.class); + } + + /** + * Convert an instance of PetWithRequiredTags to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Pig.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Pig.java new file mode 100644 index 000000000000..3d5d69b52cf1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Pig.java @@ -0,0 +1,406 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Pig extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Pig.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Pig instance itself + */ + public Pig putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(Pig instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(Pig value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 Pig + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("className") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'className' is missing."); + } + String discriminatorValue = jsonObject.get("className").getAsString(); + if ("BasquePig".equals(discriminatorValue)) { + BasquePig.validateJsonElement(jsonElement); + return; + } + if ("DanishPig".equals(discriminatorValue)) { + DanishPig.validateJsonElement(jsonElement); + return; + } + // deserialize BasquePig + try { + // validate the JSON object to see if any exception is thrown + BasquePig.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BasquePig failed with `%s`.", e.getMessage())); + } + + // deserialize DanishPig + try { + // validate the JSON object to see if any exception is thrown + DanishPig.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for DanishPig failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Pig: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Pig.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Pig' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterBasquePig = gson.getDelegateAdapter(this, TypeToken.get(BasquePig.class)); + final TypeAdapter adapterDanishPig = gson.getDelegateAdapter(this, TypeToken.get(DanishPig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Pig value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `BasquePig` + if (value.getActualInstance() instanceof BasquePig) { + element = adapterBasquePig.toJsonTree((BasquePig)value.getActualInstance()); + } + // check if the actual instance is of the type `DanishPig` + if (value.getActualInstance() instanceof DanishPig) { + element = adapterDanishPig.toJsonTree((DanishPig)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: BasquePig, DanishPig"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public Pig read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("className") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'className' is missing."); + } + String discriminatorValue = jsonObject.get("className").getAsString(); + if ("BasquePig".equals(discriminatorValue)) { + deserialized = adapterBasquePig.fromJsonTree(jsonElement); + Pig ret = new Pig(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("DanishPig".equals(discriminatorValue)) { + deserialized = adapterDanishPig.fromJsonTree(jsonElement); + Pig ret = new Pig(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize BasquePig + try { + // validate the JSON object to see if any exception is thrown + BasquePig.validateJsonElement(jsonElement); + actualAdapter = adapterBasquePig; + match++; + log.log(Level.FINER, "Input data matches schema 'BasquePig'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BasquePig failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'BasquePig'", e); + } + + // deserialize DanishPig + try { + // validate the JSON object to see if any exception is thrown + DanishPig.validateJsonElement(jsonElement); + actualAdapter = adapterDanishPig; + match++; + log.log(Level.FINER, "Input data matches schema 'DanishPig'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for DanishPig failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'DanishPig'", e); + } + + if (match == 1) { + Pig ret = new Pig(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Pig: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Pig() { + super("oneOf", Boolean.FALSE); + } + + public Pig(BasquePig o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Pig(DanishPig o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("BasquePig", BasquePig.class); + schemas.put("DanishPig", DanishPig.class); + } + + @Override + public Map> getSchemas() { + return Pig.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * BasquePig, DanishPig + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(BasquePig.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(DanishPig.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be BasquePig, DanishPig"); + } + + /** + * Get the actual instance, which can be the following: + * BasquePig, DanishPig + * + * @return The actual instance (BasquePig, DanishPig) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `BasquePig`. If the actual instance is not `BasquePig`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `BasquePig` + * @throws ClassCastException if the instance is not `BasquePig` + */ + @SuppressWarnings("unchecked") + public BasquePig getBasquePig() throws ClassCastException { + return (BasquePig)super.getActualInstance(); + } + + /** + * Get the actual instance of `DanishPig`. If the actual instance is not `DanishPig`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `DanishPig` + * @throws ClassCastException if the instance is not `DanishPig` + */ + @SuppressWarnings("unchecked") + public DanishPig getDanishPig() throws ClassCastException { + return (DanishPig)super.getActualInstance(); + } + + + + /** + * Create an instance of Pig given an JSON string + * + * @param jsonString JSON string + * @return An instance of Pig + * @throws IOException if the JSON string is invalid with respect to Pig + */ + public static Pig fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Pig.class); + } + + /** + * Convert an instance of Pig to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PropertyNameCollision.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PropertyNameCollision.java new file mode 100644 index 000000000000..44626f5a7a79 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/PropertyNameCollision.java @@ -0,0 +1,336 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * PropertyNameCollision + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class PropertyNameCollision { + public static final String SERIALIZED_NAME_UNDERSCORE_TYPE = "_type"; + @SerializedName(SERIALIZED_NAME_UNDERSCORE_TYPE) + @javax.annotation.Nullable + private String underscoreType; + + public static final String SERIALIZED_NAME_TYPE = "type"; + @SerializedName(SERIALIZED_NAME_TYPE) + @javax.annotation.Nullable + private String type; + + public static final String SERIALIZED_NAME_TYPE_WITH_UNDERSCORE = "type_"; + @SerializedName(SERIALIZED_NAME_TYPE_WITH_UNDERSCORE) + @javax.annotation.Nullable + private String typeWithUnderscore; + + public PropertyNameCollision() { + } + + public PropertyNameCollision underscoreType(@javax.annotation.Nullable String underscoreType) { + this.underscoreType = underscoreType; + return this; + } + + /** + * Get underscoreType + * @return underscoreType + */ + @javax.annotation.Nullable + + public String getUnderscoreType() { + return underscoreType; + } + + public void setUnderscoreType(@javax.annotation.Nullable String underscoreType) { + this.underscoreType = underscoreType; + } + + + public PropertyNameCollision type(@javax.annotation.Nullable String type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @javax.annotation.Nullable + + public String getType() { + return type; + } + + public void setType(@javax.annotation.Nullable String type) { + this.type = type; + } + + + public PropertyNameCollision typeWithUnderscore(@javax.annotation.Nullable String typeWithUnderscore) { + this.typeWithUnderscore = typeWithUnderscore; + return this; + } + + /** + * Get typeWithUnderscore + * @return typeWithUnderscore + */ + @javax.annotation.Nullable + + public String getTypeWithUnderscore() { + return typeWithUnderscore; + } + + public void setTypeWithUnderscore(@javax.annotation.Nullable String typeWithUnderscore) { + this.typeWithUnderscore = typeWithUnderscore; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the PropertyNameCollision instance itself + */ + public PropertyNameCollision putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + PropertyNameCollision propertyNameCollision = (PropertyNameCollision) o; + return Objects.equals(this.underscoreType, propertyNameCollision.underscoreType) && + Objects.equals(this.type, propertyNameCollision.type) && + Objects.equals(this.typeWithUnderscore, propertyNameCollision.typeWithUnderscore)&& + Objects.equals(this.additionalProperties, propertyNameCollision.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(underscoreType, type, typeWithUnderscore, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class PropertyNameCollision {\n"); + sb.append(" underscoreType: ").append(toIndentedString(underscoreType)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" typeWithUnderscore: ").append(toIndentedString(typeWithUnderscore)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("_type", "type", "type_")); + + // 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 PropertyNameCollision + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!PropertyNameCollision.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in PropertyNameCollision is not found in the empty JSON string", PropertyNameCollision.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("_type") != null && !jsonObj.get("_type").isJsonNull()) && !jsonObj.get("_type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_type").toString())); + } + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); + } + if ((jsonObj.get("type_") != null && !jsonObj.get("type_").isJsonNull()) && !jsonObj.get("type_").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `type_` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type_").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!PropertyNameCollision.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'PropertyNameCollision' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(PropertyNameCollision.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, PropertyNameCollision value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public PropertyNameCollision read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + PropertyNameCollision instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of PropertyNameCollision given an JSON string + * + * @param jsonString JSON string + * @return An instance of PropertyNameCollision + * @throws IOException if the JSON string is invalid with respect to PropertyNameCollision + */ + public static PropertyNameCollision fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, PropertyNameCollision.class); + } + + /** + * Convert an instance of PropertyNameCollision to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Quadrilateral.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Quadrilateral.java new file mode 100644 index 000000000000..2d0403338284 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Quadrilateral.java @@ -0,0 +1,406 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Quadrilateral extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Quadrilateral.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Quadrilateral instance itself + */ + public Quadrilateral putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(Quadrilateral instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(Quadrilateral value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 Quadrilateral + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("quadrilateralType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'quadrilateralType' is missing."); + } + String discriminatorValue = jsonObject.get("quadrilateralType").getAsString(); + if ("ComplexQuadrilateral".equals(discriminatorValue)) { + ComplexQuadrilateral.validateJsonElement(jsonElement); + return; + } + if ("SimpleQuadrilateral".equals(discriminatorValue)) { + SimpleQuadrilateral.validateJsonElement(jsonElement); + return; + } + // deserialize SimpleQuadrilateral + try { + // validate the JSON object to see if any exception is thrown + SimpleQuadrilateral.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for SimpleQuadrilateral failed with `%s`.", e.getMessage())); + } + + // deserialize ComplexQuadrilateral + try { + // validate the JSON object to see if any exception is thrown + ComplexQuadrilateral.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for ComplexQuadrilateral failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Quadrilateral: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Quadrilateral.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Quadrilateral' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterSimpleQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(SimpleQuadrilateral.class)); + final TypeAdapter adapterComplexQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(ComplexQuadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Quadrilateral value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `SimpleQuadrilateral` + if (value.getActualInstance() instanceof SimpleQuadrilateral) { + element = adapterSimpleQuadrilateral.toJsonTree((SimpleQuadrilateral)value.getActualInstance()); + } + // check if the actual instance is of the type `ComplexQuadrilateral` + if (value.getActualInstance() instanceof ComplexQuadrilateral) { + element = adapterComplexQuadrilateral.toJsonTree((ComplexQuadrilateral)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: ComplexQuadrilateral, SimpleQuadrilateral"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public Quadrilateral read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("quadrilateralType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'quadrilateralType' is missing."); + } + String discriminatorValue = jsonObject.get("quadrilateralType").getAsString(); + if ("ComplexQuadrilateral".equals(discriminatorValue)) { + deserialized = adapterComplexQuadrilateral.fromJsonTree(jsonElement); + Quadrilateral ret = new Quadrilateral(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("SimpleQuadrilateral".equals(discriminatorValue)) { + deserialized = adapterSimpleQuadrilateral.fromJsonTree(jsonElement); + Quadrilateral ret = new Quadrilateral(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize SimpleQuadrilateral + try { + // validate the JSON object to see if any exception is thrown + SimpleQuadrilateral.validateJsonElement(jsonElement); + actualAdapter = adapterSimpleQuadrilateral; + match++; + log.log(Level.FINER, "Input data matches schema 'SimpleQuadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for SimpleQuadrilateral failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'SimpleQuadrilateral'", e); + } + + // deserialize ComplexQuadrilateral + try { + // validate the JSON object to see if any exception is thrown + ComplexQuadrilateral.validateJsonElement(jsonElement); + actualAdapter = adapterComplexQuadrilateral; + match++; + log.log(Level.FINER, "Input data matches schema 'ComplexQuadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for ComplexQuadrilateral failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'ComplexQuadrilateral'", e); + } + + if (match == 1) { + Quadrilateral ret = new Quadrilateral(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Quadrilateral: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Quadrilateral() { + super("oneOf", Boolean.FALSE); + } + + public Quadrilateral(SimpleQuadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Quadrilateral(ComplexQuadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("SimpleQuadrilateral", SimpleQuadrilateral.class); + schemas.put("ComplexQuadrilateral", ComplexQuadrilateral.class); + } + + @Override + public Map> getSchemas() { + return Quadrilateral.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * ComplexQuadrilateral, SimpleQuadrilateral + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(SimpleQuadrilateral.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(ComplexQuadrilateral.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be ComplexQuadrilateral, SimpleQuadrilateral"); + } + + /** + * Get the actual instance, which can be the following: + * ComplexQuadrilateral, SimpleQuadrilateral + * + * @return The actual instance (ComplexQuadrilateral, SimpleQuadrilateral) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `SimpleQuadrilateral`. If the actual instance is not `SimpleQuadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `SimpleQuadrilateral` + * @throws ClassCastException if the instance is not `SimpleQuadrilateral` + */ + @SuppressWarnings("unchecked") + public SimpleQuadrilateral getSimpleQuadrilateral() throws ClassCastException { + return (SimpleQuadrilateral)super.getActualInstance(); + } + + /** + * Get the actual instance of `ComplexQuadrilateral`. If the actual instance is not `ComplexQuadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `ComplexQuadrilateral` + * @throws ClassCastException if the instance is not `ComplexQuadrilateral` + */ + @SuppressWarnings("unchecked") + public ComplexQuadrilateral getComplexQuadrilateral() throws ClassCastException { + return (ComplexQuadrilateral)super.getActualInstance(); + } + + + + /** + * Create an instance of Quadrilateral given an JSON string + * + * @param jsonString JSON string + * @return An instance of Quadrilateral + * @throws IOException if the JSON string is invalid with respect to Quadrilateral + */ + public static Quadrilateral fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Quadrilateral.class); + } + + /** + * Convert an instance of Quadrilateral to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java new file mode 100644 index 000000000000..7ba959ee9b9d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java @@ -0,0 +1,283 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * QuadrilateralInterface + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class QuadrilateralInterface { + public static final String SERIALIZED_NAME_QUADRILATERAL_TYPE = "quadrilateralType"; + @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) + @javax.annotation.Nonnull + private String quadrilateralType; + + public QuadrilateralInterface() { + } + + public QuadrilateralInterface quadrilateralType(@javax.annotation.Nonnull String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + return this; + } + + /** + * Get quadrilateralType + * @return quadrilateralType + */ + @javax.annotation.Nonnull + + public String getQuadrilateralType() { + return quadrilateralType; + } + + public void setQuadrilateralType(@javax.annotation.Nonnull String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the QuadrilateralInterface instance itself + */ + public QuadrilateralInterface putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + QuadrilateralInterface quadrilateralInterface = (QuadrilateralInterface) o; + return Objects.equals(this.quadrilateralType, quadrilateralInterface.quadrilateralType)&& + Objects.equals(this.additionalProperties, quadrilateralInterface.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(quadrilateralType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class QuadrilateralInterface {\n"); + sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("quadrilateralType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("quadrilateralType")); + } + + /** + * 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 QuadrilateralInterface + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!QuadrilateralInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in QuadrilateralInterface is not found in the empty JSON string", QuadrilateralInterface.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : QuadrilateralInterface.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("quadrilateralType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `quadrilateralType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("quadrilateralType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!QuadrilateralInterface.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'QuadrilateralInterface' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(QuadrilateralInterface.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, QuadrilateralInterface value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public QuadrilateralInterface read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + QuadrilateralInterface instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of QuadrilateralInterface given an JSON string + * + * @param jsonString JSON string + * @return An instance of QuadrilateralInterface + * @throws IOException if the JSON string is invalid with respect to QuadrilateralInterface + */ + public static QuadrilateralInterface fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, QuadrilateralInterface.class); + } + + /** + * Convert an instance of QuadrilateralInterface to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java new file mode 100644 index 000000000000..0883b4cfc99a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -0,0 +1,308 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ReadOnlyFirst + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ReadOnlyFirst { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + @javax.annotation.Nullable + private String bar; + + public static final String SERIALIZED_NAME_BAZ = "baz"; + @SerializedName(SERIALIZED_NAME_BAZ) + @javax.annotation.Nullable + private String baz; + + public ReadOnlyFirst() { + } + + /** + * Constructor with only readonly parameters + */ + public ReadOnlyFirst( + String bar + ) { + this(); + this.bar = bar; + } + + /** + * Get bar + * @return bar + */ + @javax.annotation.Nullable + + public String getBar() { + return bar; + } + + + + public ReadOnlyFirst baz(@javax.annotation.Nullable String baz) { + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + */ + @javax.annotation.Nullable + + public String getBaz() { + return baz; + } + + public void setBaz(@javax.annotation.Nullable String baz) { + this.baz = baz; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ReadOnlyFirst instance itself + */ + public ReadOnlyFirst putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz)&& + Objects.equals(this.additionalProperties, readOnlyFirst.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("bar", "baz")); + + // 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 ReadOnlyFirst + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ReadOnlyFirst.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ReadOnlyFirst is not found in the empty JSON string", ReadOnlyFirst.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString())); + } + if ((jsonObj.get("baz") != null && !jsonObj.get("baz").isJsonNull()) && !jsonObj.get("baz").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `baz` to be a primitive type in the JSON string but got `%s`", jsonObj.get("baz").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ReadOnlyFirst.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ReadOnlyFirst' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ReadOnlyFirst.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ReadOnlyFirst value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ReadOnlyFirst read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ReadOnlyFirst instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ReadOnlyFirst given an JSON string + * + * @param jsonString JSON string + * @return An instance of ReadOnlyFirst + * @throws IOException if the JSON string is invalid with respect to ReadOnlyFirst + */ + public static ReadOnlyFirst fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ReadOnlyFirst.class); + } + + /** + * Convert an instance of ReadOnlyFirst to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/RequiredNullableBody.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/RequiredNullableBody.java new file mode 100644 index 000000000000..9d627e6a9c61 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/RequiredNullableBody.java @@ -0,0 +1,766 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * RequiredNullableBody + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class RequiredNullableBody { + public static final String SERIALIZED_NAME_INTEGER_PROP = "integer_prop"; + @SerializedName(SERIALIZED_NAME_INTEGER_PROP) + @javax.annotation.Nullable + private Integer integerProp; + + public static final String SERIALIZED_NAME_NUMBER_PROP = "number_prop"; + @SerializedName(SERIALIZED_NAME_NUMBER_PROP) + @javax.annotation.Nullable + private BigDecimal numberProp; + + public static final String SERIALIZED_NAME_BOOLEAN_PROP = "boolean_prop"; + @SerializedName(SERIALIZED_NAME_BOOLEAN_PROP) + @javax.annotation.Nullable + private Boolean booleanProp; + + public static final String SERIALIZED_NAME_STRING_PROP = "string_prop"; + @SerializedName(SERIALIZED_NAME_STRING_PROP) + @javax.annotation.Nullable + private String stringProp; + + public static final String SERIALIZED_NAME_DATE_PROP = "date_prop"; + @SerializedName(SERIALIZED_NAME_DATE_PROP) + @javax.annotation.Nullable + private LocalDate dateProp; + + public static final String SERIALIZED_NAME_DATETIME_PROP = "datetime_prop"; + @SerializedName(SERIALIZED_NAME_DATETIME_PROP) + @javax.annotation.Nullable + private OffsetDateTime datetimeProp; + + public static final String SERIALIZED_NAME_ARRAY_NULLABLE_PROP = "array_nullable_prop"; + @SerializedName(SERIALIZED_NAME_ARRAY_NULLABLE_PROP) + @javax.annotation.Nullable + private List arrayNullableProp; + + public static final String SERIALIZED_NAME_ARRAY_AND_ITEMS_NULLABLE_PROP = "array_and_items_nullable_prop"; + @SerializedName(SERIALIZED_NAME_ARRAY_AND_ITEMS_NULLABLE_PROP) + @javax.annotation.Nullable + private List arrayAndItemsNullableProp; + + public static final String SERIALIZED_NAME_ARRAY_ITEMS_NULLABLE = "array_items_nullable"; + @SerializedName(SERIALIZED_NAME_ARRAY_ITEMS_NULLABLE) + @javax.annotation.Nonnull + private List arrayItemsNullable = new ArrayList<>(); + + public static final String SERIALIZED_NAME_OBJECT_NULLABLE_PROP = "object_nullable_prop"; + @SerializedName(SERIALIZED_NAME_OBJECT_NULLABLE_PROP) + @javax.annotation.Nullable + private Map objectNullableProp; + + public static final String SERIALIZED_NAME_OBJECT_AND_ITEMS_NULLABLE_PROP = "object_and_items_nullable_prop"; + @SerializedName(SERIALIZED_NAME_OBJECT_AND_ITEMS_NULLABLE_PROP) + @javax.annotation.Nullable + private Map objectAndItemsNullableProp; + + public static final String SERIALIZED_NAME_OBJECT_ITEMS_NULLABLE = "object_items_nullable"; + @SerializedName(SERIALIZED_NAME_OBJECT_ITEMS_NULLABLE) + @javax.annotation.Nonnull + private Map objectItemsNullable = new HashMap<>(); + + public static final String SERIALIZED_NAME_CUSTOM_REF_ENUM = "custom_ref_enum"; + @SerializedName(SERIALIZED_NAME_CUSTOM_REF_ENUM) + @javax.annotation.Nullable + private NullableEnum customRefEnum; + + /** + * Gets or Sets customEnum + */ + @JsonAdapter(CustomEnumEnum.Adapter.class) + public enum CustomEnumEnum { + CUSTOM("custom"); + + private String value; + + CustomEnumEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static CustomEnumEnum fromValue(String value) { + for (CustomEnumEnum b : CustomEnumEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final CustomEnumEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public CustomEnumEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return CustomEnumEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + CustomEnumEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_CUSTOM_ENUM = "custom_enum"; + @SerializedName(SERIALIZED_NAME_CUSTOM_ENUM) + @javax.annotation.Nullable + private CustomEnumEnum customEnum; + + public RequiredNullableBody() { + } + + public RequiredNullableBody integerProp(@javax.annotation.Nullable Integer integerProp) { + this.integerProp = integerProp; + return this; + } + + /** + * Get integerProp + * @return integerProp + */ + @javax.annotation.Nullable + + public Integer getIntegerProp() { + return integerProp; + } + + public void setIntegerProp(@javax.annotation.Nullable Integer integerProp) { + this.integerProp = integerProp; + } + + + public RequiredNullableBody numberProp(@javax.annotation.Nullable BigDecimal numberProp) { + this.numberProp = numberProp; + return this; + } + + /** + * Get numberProp + * @return numberProp + */ + @javax.annotation.Nullable + + public BigDecimal getNumberProp() { + return numberProp; + } + + public void setNumberProp(@javax.annotation.Nullable BigDecimal numberProp) { + this.numberProp = numberProp; + } + + + public RequiredNullableBody booleanProp(@javax.annotation.Nullable Boolean booleanProp) { + this.booleanProp = booleanProp; + return this; + } + + /** + * Get booleanProp + * @return booleanProp + */ + @javax.annotation.Nullable + + public Boolean getBooleanProp() { + return booleanProp; + } + + public void setBooleanProp(@javax.annotation.Nullable Boolean booleanProp) { + this.booleanProp = booleanProp; + } + + + public RequiredNullableBody stringProp(@javax.annotation.Nullable String stringProp) { + this.stringProp = stringProp; + return this; + } + + /** + * Get stringProp + * @return stringProp + */ + @javax.annotation.Nullable + + public String getStringProp() { + return stringProp; + } + + public void setStringProp(@javax.annotation.Nullable String stringProp) { + this.stringProp = stringProp; + } + + + public RequiredNullableBody dateProp(@javax.annotation.Nullable LocalDate dateProp) { + this.dateProp = dateProp; + return this; + } + + /** + * Get dateProp + * @return dateProp + */ + @javax.annotation.Nullable + + public LocalDate getDateProp() { + return dateProp; + } + + public void setDateProp(@javax.annotation.Nullable LocalDate dateProp) { + this.dateProp = dateProp; + } + + + public RequiredNullableBody datetimeProp(@javax.annotation.Nullable OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + return this; + } + + /** + * Get datetimeProp + * @return datetimeProp + */ + @javax.annotation.Nullable + + public OffsetDateTime getDatetimeProp() { + return datetimeProp; + } + + public void setDatetimeProp(@javax.annotation.Nullable OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + } + + + public RequiredNullableBody arrayNullableProp(@javax.annotation.Nullable List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + return this; + } + + public RequiredNullableBody addArrayNullablePropItem(Object arrayNullablePropItem) { + if (this.arrayNullableProp == null) { + this.arrayNullableProp = new ArrayList<>(); + } + this.arrayNullableProp.add(arrayNullablePropItem); + return this; + } + + /** + * Get arrayNullableProp + * @return arrayNullableProp + */ + @javax.annotation.Nullable + + public List getArrayNullableProp() { + return arrayNullableProp; + } + + public void setArrayNullableProp(@javax.annotation.Nullable List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + } + + + public RequiredNullableBody arrayAndItemsNullableProp(@javax.annotation.Nullable List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + return this; + } + + public RequiredNullableBody addArrayAndItemsNullablePropItem(Object arrayAndItemsNullablePropItem) { + if (this.arrayAndItemsNullableProp == null) { + this.arrayAndItemsNullableProp = new ArrayList<>(); + } + this.arrayAndItemsNullableProp.add(arrayAndItemsNullablePropItem); + return this; + } + + /** + * Get arrayAndItemsNullableProp + * @return arrayAndItemsNullableProp + */ + @javax.annotation.Nullable + + public List getArrayAndItemsNullableProp() { + return arrayAndItemsNullableProp; + } + + public void setArrayAndItemsNullableProp(@javax.annotation.Nullable List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + } + + + public RequiredNullableBody arrayItemsNullable(@javax.annotation.Nonnull List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + return this; + } + + public RequiredNullableBody addArrayItemsNullableItem(Object arrayItemsNullableItem) { + if (this.arrayItemsNullable == null) { + this.arrayItemsNullable = new ArrayList<>(); + } + this.arrayItemsNullable.add(arrayItemsNullableItem); + return this; + } + + /** + * Get arrayItemsNullable + * @return arrayItemsNullable + */ + @javax.annotation.Nonnull + + public List getArrayItemsNullable() { + return arrayItemsNullable; + } + + public void setArrayItemsNullable(@javax.annotation.Nonnull List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + } + + + public RequiredNullableBody objectNullableProp(@javax.annotation.Nullable Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + return this; + } + + public RequiredNullableBody putObjectNullablePropItem(String key, Object objectNullablePropItem) { + if (this.objectNullableProp == null) { + this.objectNullableProp = new HashMap<>(); + } + this.objectNullableProp.put(key, objectNullablePropItem); + return this; + } + + /** + * Get objectNullableProp + * @return objectNullableProp + */ + @javax.annotation.Nullable + + public Map getObjectNullableProp() { + return objectNullableProp; + } + + public void setObjectNullableProp(@javax.annotation.Nullable Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + } + + + public RequiredNullableBody objectAndItemsNullableProp(@javax.annotation.Nullable Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + return this; + } + + public RequiredNullableBody putObjectAndItemsNullablePropItem(String key, Object objectAndItemsNullablePropItem) { + if (this.objectAndItemsNullableProp == null) { + this.objectAndItemsNullableProp = new HashMap<>(); + } + this.objectAndItemsNullableProp.put(key, objectAndItemsNullablePropItem); + return this; + } + + /** + * Get objectAndItemsNullableProp + * @return objectAndItemsNullableProp + */ + @javax.annotation.Nullable + + public Map getObjectAndItemsNullableProp() { + return objectAndItemsNullableProp; + } + + public void setObjectAndItemsNullableProp(@javax.annotation.Nullable Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + } + + + public RequiredNullableBody objectItemsNullable(@javax.annotation.Nonnull Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + return this; + } + + public RequiredNullableBody putObjectItemsNullableItem(String key, Object objectItemsNullableItem) { + if (this.objectItemsNullable == null) { + this.objectItemsNullable = new HashMap<>(); + } + this.objectItemsNullable.put(key, objectItemsNullableItem); + return this; + } + + /** + * Get objectItemsNullable + * @return objectItemsNullable + */ + @javax.annotation.Nonnull + + public Map getObjectItemsNullable() { + return objectItemsNullable; + } + + public void setObjectItemsNullable(@javax.annotation.Nonnull Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + } + + + public RequiredNullableBody customRefEnum(@javax.annotation.Nullable NullableEnum customRefEnum) { + this.customRefEnum = customRefEnum; + return this; + } + + /** + * Get customRefEnum + * @return customRefEnum + */ + @javax.annotation.Nullable + + public NullableEnum getCustomRefEnum() { + return customRefEnum; + } + + public void setCustomRefEnum(@javax.annotation.Nullable NullableEnum customRefEnum) { + this.customRefEnum = customRefEnum; + } + + + public RequiredNullableBody customEnum(@javax.annotation.Nullable CustomEnumEnum customEnum) { + this.customEnum = customEnum; + return this; + } + + /** + * Get customEnum + * @return customEnum + */ + @javax.annotation.Nullable + + public CustomEnumEnum getCustomEnum() { + return customEnum; + } + + public void setCustomEnum(@javax.annotation.Nullable CustomEnumEnum customEnum) { + this.customEnum = customEnum; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the RequiredNullableBody instance itself + */ + public RequiredNullableBody putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + RequiredNullableBody requiredNullableBody = (RequiredNullableBody) o; + return Objects.equals(this.integerProp, requiredNullableBody.integerProp) && + Objects.equals(this.numberProp, requiredNullableBody.numberProp) && + Objects.equals(this.booleanProp, requiredNullableBody.booleanProp) && + Objects.equals(this.stringProp, requiredNullableBody.stringProp) && + Objects.equals(this.dateProp, requiredNullableBody.dateProp) && + Objects.equals(this.datetimeProp, requiredNullableBody.datetimeProp) && + Objects.equals(this.arrayNullableProp, requiredNullableBody.arrayNullableProp) && + Objects.equals(this.arrayAndItemsNullableProp, requiredNullableBody.arrayAndItemsNullableProp) && + Objects.equals(this.arrayItemsNullable, requiredNullableBody.arrayItemsNullable) && + Objects.equals(this.objectNullableProp, requiredNullableBody.objectNullableProp) && + Objects.equals(this.objectAndItemsNullableProp, requiredNullableBody.objectAndItemsNullableProp) && + Objects.equals(this.objectItemsNullable, requiredNullableBody.objectItemsNullable) && + Objects.equals(this.customRefEnum, requiredNullableBody.customRefEnum) && + Objects.equals(this.customEnum, requiredNullableBody.customEnum)&& + Objects.equals(this.additionalProperties, requiredNullableBody.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, customRefEnum, customEnum, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class RequiredNullableBody {\n"); + sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); + sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); + sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); + sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); + sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); + sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); + sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); + sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); + sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); + sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); + sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); + sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append(" customRefEnum: ").append(toIndentedString(customRefEnum)).append("\n"); + sb.append(" customEnum: ").append(toIndentedString(customEnum)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable", "custom_ref_enum", "custom_enum")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable", "custom_ref_enum", "custom_enum")); + } + + /** + * 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 RequiredNullableBody + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!RequiredNullableBody.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in RequiredNullableBody is not found in the empty JSON string", RequiredNullableBody.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : RequiredNullableBody.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("string_prop") != null && !jsonObj.get("string_prop").isJsonNull()) && !jsonObj.get("string_prop").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `string_prop` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_prop").toString())); + } + // ensure the required json array is present + if (jsonObj.get("array_nullable_prop") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("array_nullable_prop").isJsonArray() && !jsonObj.get("array_nullable_prop").isJsonNull()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_nullable_prop` to be an array in the JSON string but got `%s`", jsonObj.get("array_nullable_prop").toString())); + } + // ensure the required json array is present + if (jsonObj.get("array_and_items_nullable_prop") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("array_and_items_nullable_prop").isJsonArray() && !jsonObj.get("array_and_items_nullable_prop").isJsonNull()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_and_items_nullable_prop` to be an array in the JSON string but got `%s`", jsonObj.get("array_and_items_nullable_prop").toString())); + } + // ensure the required json array is present + if (jsonObj.get("array_items_nullable") == null) { + throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`"); + } else if (!jsonObj.get("array_items_nullable").isJsonArray()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `array_items_nullable` to be an array in the JSON string but got `%s`", jsonObj.get("array_items_nullable").toString())); + } + if (jsonObj.get("custom_ref_enum") != null && !jsonObj.get("custom_ref_enum").isJsonNull()) { + // validate the required field `custom_ref_enum` + NullableEnum.validateJsonElement(jsonObj.get("custom_ref_enum")); + } + if ((jsonObj.get("custom_enum") != null && !jsonObj.get("custom_enum").isJsonNull()) && !jsonObj.get("custom_enum").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `custom_enum` to be a primitive type in the JSON string but got `%s`", jsonObj.get("custom_enum").toString())); + } + if (jsonObj.get("custom_enum") != null && !jsonObj.get("custom_enum").isJsonNull()) { + // validate the required field `custom_enum` + CustomEnumEnum.validateJsonElement(jsonObj.get("custom_enum")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!RequiredNullableBody.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'RequiredNullableBody' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(RequiredNullableBody.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, RequiredNullableBody value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public RequiredNullableBody read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + RequiredNullableBody instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of RequiredNullableBody given an JSON string + * + * @param jsonString JSON string + * @return An instance of RequiredNullableBody + * @throws IOException if the JSON string is invalid with respect to RequiredNullableBody + */ + public static RequiredNullableBody fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, RequiredNullableBody.class); + } + + /** + * Convert an instance of RequiredNullableBody to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Scalar.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Scalar.java new file mode 100644 index 000000000000..bbb4bcc52194 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Scalar.java @@ -0,0 +1,490 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Scalar extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Scalar.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Scalar instance itself + */ + public Scalar putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(Scalar instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(Scalar value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 Scalar + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize UUID + try { + // validate the JSON object to see if any exception is thrown + UUID.fromString(jsonElement.getAsString()); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for UUID failed with `%s`.", e.getMessage())); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + } + + // deserialize BigDecimal + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BigDecimal failed with `%s`.", e.getMessage())); + } + + // deserialize Boolean + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isBoolean()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Boolean in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Boolean failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Scalar: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Scalar.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Scalar' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterUUID = gson.getDelegateAdapter(this, TypeToken.get(UUID.class)); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + final TypeAdapter adapterBigDecimal = gson.getDelegateAdapter(this, TypeToken.get(BigDecimal.class)); + final TypeAdapter adapterBoolean = gson.getDelegateAdapter(this, TypeToken.get(Boolean.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Scalar value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `UUID` + if (value.getActualInstance() instanceof UUID) { + element = adapterUUID.toJsonTree((UUID)value.getActualInstance()); + } + // check if the actual instance is of the type `String` + if (value.getActualInstance() instanceof String) { + element = adapterString.toJsonTree((String)value.getActualInstance()); + } + // check if the actual instance is of the type `BigDecimal` + if (value.getActualInstance() instanceof BigDecimal) { + element = adapterBigDecimal.toJsonTree((BigDecimal)value.getActualInstance()); + } + // check if the actual instance is of the type `Boolean` + if (value.getActualInstance() instanceof Boolean) { + element = adapterBoolean.toJsonTree((Boolean)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: BigDecimal, Boolean, String, UUID"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public Scalar read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize UUID + try { + // validate the JSON object to see if any exception is thrown + UUID.fromString(jsonElement.getAsString()); + actualAdapter = adapterUUID; + match++; + log.log(Level.FINER, "Input data matches schema 'UUID'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for UUID failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'UUID'", e); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + // deserialize BigDecimal + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterBigDecimal; + match++; + log.log(Level.FINER, "Input data matches schema 'BigDecimal'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BigDecimal failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'BigDecimal'", e); + } + + // deserialize Boolean + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isBoolean()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Boolean in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterBoolean; + match++; + log.log(Level.FINER, "Input data matches schema 'Boolean'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Boolean failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Boolean'", e); + } + + if (match == 1) { + Scalar ret = new Scalar(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Scalar: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Scalar() { + super("oneOf", Boolean.FALSE); + } + + public Scalar(UUID o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Scalar(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Scalar(BigDecimal o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Scalar(Boolean o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("UUID", UUID.class); + schemas.put("String", String.class); + schemas.put("BigDecimal", BigDecimal.class); + schemas.put("Boolean", Boolean.class); + } + + @Override + public Map> getSchemas() { + return Scalar.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * BigDecimal, Boolean, String, UUID + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(UUID.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(String.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(BigDecimal.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Boolean.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be BigDecimal, Boolean, String, UUID"); + } + + /** + * Get the actual instance, which can be the following: + * BigDecimal, Boolean, String, UUID + * + * @return The actual instance (BigDecimal, Boolean, String, UUID) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `UUID`. If the actual instance is not `UUID`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `UUID` + * @throws ClassCastException if the instance is not `UUID` + */ + @SuppressWarnings("unchecked") + public UUID getUUID() throws ClassCastException { + return (UUID)super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + @SuppressWarnings("unchecked") + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + /** + * Get the actual instance of `BigDecimal`. If the actual instance is not `BigDecimal`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `BigDecimal` + * @throws ClassCastException if the instance is not `BigDecimal` + */ + @SuppressWarnings("unchecked") + public BigDecimal getBigDecimal() throws ClassCastException { + return (BigDecimal)super.getActualInstance(); + } + + /** + * Get the actual instance of `Boolean`. If the actual instance is not `Boolean`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Boolean` + * @throws ClassCastException if the instance is not `Boolean` + */ + @SuppressWarnings("unchecked") + public Boolean getBoolean() throws ClassCastException { + return (Boolean)super.getActualInstance(); + } + + + + /** + * Create an instance of Scalar given an JSON string + * + * @param jsonString JSON string + * @return An instance of Scalar + * @throws IOException if the JSON string is invalid with respect to Scalar + */ + public static Scalar fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Scalar.class); + } + + /** + * Convert an instance of Scalar to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ScalarAnyOf.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ScalarAnyOf.java new file mode 100644 index 000000000000..6db81c37013a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ScalarAnyOf.java @@ -0,0 +1,484 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ScalarAnyOf extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ScalarAnyOf.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ScalarAnyOf instance itself + */ + public ScalarAnyOf putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched anyOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(ScalarAnyOf instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched anyOf schema. + */ + private static void writeUnconsumedProperties(ScalarAnyOf value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 ScalarAnyOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + List errorMessages = new ArrayList<>(); + int matches = 0; + + try { + // validate the JSON object to see if any exception is thrown + UUID.fromString(jsonElement.getAsString()); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for UUID failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BigDecimal failed with `%s`.", e.getMessage())); + } + + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isBoolean()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Boolean in the JSON string but got `%s`", jsonElement.toString())); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Boolean failed with `%s`.", e.getMessage())); + } + + + if (matches == 0) { + throw new IOException(String.format("Failed deserialization for ScalarAnyOf: no match found. %s", errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ScalarAnyOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ScalarAnyOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterUUID = gson.getDelegateAdapter(this, TypeToken.get(UUID.class)); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + final TypeAdapter adapterBigDecimal = gson.getDelegateAdapter(this, TypeToken.get(BigDecimal.class)); + final TypeAdapter adapterBoolean = gson.getDelegateAdapter(this, TypeToken.get(Boolean.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ScalarAnyOf value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `UUID` + if (value.getActualInstance() instanceof UUID) { + element = adapterUUID.toJsonTree((UUID)value.getActualInstance()); + } + // check if the actual instance is of the type `String` + if (value.getActualInstance() instanceof String) { + element = adapterString.toJsonTree((String)value.getActualInstance()); + } + // check if the actual instance is of the type `BigDecimal` + if (value.getActualInstance() instanceof BigDecimal) { + element = adapterBigDecimal.toJsonTree((BigDecimal)value.getActualInstance()); + } + // check if the actual instance is of the type `Boolean` + if (value.getActualInstance() instanceof Boolean) { + element = adapterBoolean.toJsonTree((Boolean)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: BigDecimal, Boolean, String, UUID"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public ScalarAnyOf read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize UUID + try { + // validate the JSON object to see if any exception is thrown + UUID.fromString(jsonElement.getAsString()); + ScalarAnyOf ret = new ScalarAnyOf(); + ret.setActualInstance(adapterUUID.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for UUID failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'UUID'", e); + } + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + ScalarAnyOf ret = new ScalarAnyOf(); + ret.setActualInstance(adapterString.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + // deserialize BigDecimal + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + ScalarAnyOf ret = new ScalarAnyOf(); + ret.setActualInstance(adapterBigDecimal.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for BigDecimal failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'BigDecimal'", e); + } + + // deserialize Boolean + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isBoolean()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Boolean in the JSON string but got `%s`", jsonElement.toString())); + } + ScalarAnyOf ret = new ScalarAnyOf(); + ret.setActualInstance(adapterBoolean.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Boolean failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Boolean'", e); + } + + + throw new IOException(String.format("Failed deserialization for ScalarAnyOf: no match found. %s", errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap<>(); + + public ScalarAnyOf() { + super("anyOf", Boolean.FALSE); + } + + public ScalarAnyOf(UUID o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public ScalarAnyOf(String o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public ScalarAnyOf(BigDecimal o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public ScalarAnyOf(Boolean o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("UUID", UUID.class); + schemas.put("String", String.class); + schemas.put("BigDecimal", BigDecimal.class); + schemas.put("Boolean", Boolean.class); + } + + @Override + public Map> getSchemas() { + return ScalarAnyOf.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * BigDecimal, Boolean, String, UUID + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(UUID.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(String.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(BigDecimal.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Boolean.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be BigDecimal, Boolean, String, UUID"); + } + + /** + * Get the actual instance, which can be the following: + * BigDecimal, Boolean, String, UUID + * + * @return The actual instance (BigDecimal, Boolean, String, UUID) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `UUID`. If the actual instance is not `UUID`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `UUID` + * @throws ClassCastException if the instance is not `UUID` + */ + @SuppressWarnings("unchecked") + public UUID getUUID() throws ClassCastException { + return (UUID)super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + @SuppressWarnings("unchecked") + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + /** + * Get the actual instance of `BigDecimal`. If the actual instance is not `BigDecimal`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `BigDecimal` + * @throws ClassCastException if the instance is not `BigDecimal` + */ + @SuppressWarnings("unchecked") + public BigDecimal getBigDecimal() throws ClassCastException { + return (BigDecimal)super.getActualInstance(); + } + + /** + * Get the actual instance of `Boolean`. If the actual instance is not `Boolean`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Boolean` + * @throws ClassCastException if the instance is not `Boolean` + */ + @SuppressWarnings("unchecked") + public Boolean getBoolean() throws ClassCastException { + return (Boolean)super.getActualInstance(); + } + + + + /** + * Create an instance of ScalarAnyOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of ScalarAnyOf + * @throws IOException if the JSON string is invalid with respect to ScalarAnyOf + */ + public static ScalarAnyOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ScalarAnyOf.class); + } + + /** + * Convert an instance of ScalarAnyOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ScaleneTriangle.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ScaleneTriangle.java new file mode 100644 index 000000000000..ae1b42e45189 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ScaleneTriangle.java @@ -0,0 +1,313 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ScaleneTriangle + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ScaleneTriangle { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + @javax.annotation.Nonnull + private String shapeType; + + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + @javax.annotation.Nonnull + private String triangleType; + + public ScaleneTriangle() { + } + + public ScaleneTriangle shapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + */ + @javax.annotation.Nonnull + + public String getShapeType() { + return shapeType; + } + + public void setShapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + } + + + public ScaleneTriangle triangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + */ + @javax.annotation.Nonnull + + public String getTriangleType() { + return triangleType; + } + + public void setTriangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ScaleneTriangle instance itself + */ + public ScaleneTriangle putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ScaleneTriangle scaleneTriangle = (ScaleneTriangle) o; + return Objects.equals(this.shapeType, scaleneTriangle.shapeType) && + Objects.equals(this.triangleType, scaleneTriangle.triangleType)&& + Objects.equals(this.additionalProperties, scaleneTriangle.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, triangleType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ScaleneTriangle {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("shapeType", "triangleType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("shapeType", "triangleType")); + } + + /** + * 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 ScaleneTriangle + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ScaleneTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ScaleneTriangle is not found in the empty JSON string", ScaleneTriangle.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ScaleneTriangle.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("shapeType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); + } + if (!jsonObj.get("triangleType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ScaleneTriangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ScaleneTriangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ScaleneTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ScaleneTriangle value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ScaleneTriangle read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ScaleneTriangle instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ScaleneTriangle given an JSON string + * + * @param jsonString JSON string + * @return An instance of ScaleneTriangle + * @throws IOException if the JSON string is invalid with respect to ScaleneTriangle + */ + public static ScaleneTriangle fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ScaleneTriangle.class); + } + + /** + * Convert an instance of ScaleneTriangle to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Shape.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Shape.java new file mode 100644 index 000000000000..7d3642634478 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Shape.java @@ -0,0 +1,406 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Shape extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Shape.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Shape instance itself + */ + public Shape putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(Shape instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(Shape value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 Shape + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("shapeType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'shapeType' is missing."); + } + String discriminatorValue = jsonObject.get("shapeType").getAsString(); + if ("Quadrilateral".equals(discriminatorValue)) { + Quadrilateral.validateJsonElement(jsonElement); + return; + } + if ("Triangle".equals(discriminatorValue)) { + Triangle.validateJsonElement(jsonElement); + return; + } + // deserialize Triangle + try { + // validate the JSON object to see if any exception is thrown + Triangle.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage())); + } + + // deserialize Quadrilateral + try { + // validate the JSON object to see if any exception is thrown + Quadrilateral.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Shape: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Shape.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Shape' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class)); + final TypeAdapter adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Shape value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Triangle` + if (value.getActualInstance() instanceof Triangle) { + element = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()); + } + // check if the actual instance is of the type `Quadrilateral` + if (value.getActualInstance() instanceof Quadrilateral) { + element = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public Shape read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("shapeType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'shapeType' is missing."); + } + String discriminatorValue = jsonObject.get("shapeType").getAsString(); + if ("Quadrilateral".equals(discriminatorValue)) { + deserialized = adapterQuadrilateral.fromJsonTree(jsonElement); + Shape ret = new Shape(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("Triangle".equals(discriminatorValue)) { + deserialized = adapterTriangle.fromJsonTree(jsonElement); + Shape ret = new Shape(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Triangle + try { + // validate the JSON object to see if any exception is thrown + Triangle.validateJsonElement(jsonElement); + actualAdapter = adapterTriangle; + match++; + log.log(Level.FINER, "Input data matches schema 'Triangle'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); + } + + // deserialize Quadrilateral + try { + // validate the JSON object to see if any exception is thrown + Quadrilateral.validateJsonElement(jsonElement); + actualAdapter = adapterQuadrilateral; + match++; + log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); + } + + if (match == 1) { + Shape ret = new Shape(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Shape: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Shape() { + super("oneOf", Boolean.FALSE); + } + + public Shape(Triangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Shape(Quadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Triangle", Triangle.class); + schemas.put("Quadrilateral", Quadrilateral.class); + } + + @Override + public Map> getSchemas() { + return Shape.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Quadrilateral, Triangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Triangle.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Quadrilateral.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); + } + + /** + * Get the actual instance, which can be the following: + * Quadrilateral, Triangle + * + * @return The actual instance (Quadrilateral, Triangle) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Triangle` + * @throws ClassCastException if the instance is not `Triangle` + */ + @SuppressWarnings("unchecked") + public Triangle getTriangle() throws ClassCastException { + return (Triangle)super.getActualInstance(); + } + + /** + * Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Quadrilateral` + * @throws ClassCastException if the instance is not `Quadrilateral` + */ + @SuppressWarnings("unchecked") + public Quadrilateral getQuadrilateral() throws ClassCastException { + return (Quadrilateral)super.getActualInstance(); + } + + + + /** + * Create an instance of Shape given an JSON string + * + * @param jsonString JSON string + * @return An instance of Shape + * @throws IOException if the JSON string is invalid with respect to Shape + */ + public static Shape fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Shape.class); + } + + /** + * Convert an instance of Shape to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ShapeInterface.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ShapeInterface.java new file mode 100644 index 000000000000..a18f50f5901e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ShapeInterface.java @@ -0,0 +1,283 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * ShapeInterface + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ShapeInterface { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + @javax.annotation.Nonnull + private String shapeType; + + public ShapeInterface() { + } + + public ShapeInterface shapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + */ + @javax.annotation.Nonnull + + public String getShapeType() { + return shapeType; + } + + public void setShapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ShapeInterface instance itself + */ + public ShapeInterface putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ShapeInterface shapeInterface = (ShapeInterface) o; + return Objects.equals(this.shapeType, shapeInterface.shapeType)&& + Objects.equals(this.additionalProperties, shapeInterface.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ShapeInterface {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("shapeType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("shapeType")); + } + + /** + * 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 ShapeInterface + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!ShapeInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in ShapeInterface is not found in the empty JSON string", ShapeInterface.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ShapeInterface.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("shapeType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ShapeInterface.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ShapeInterface' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ShapeInterface.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ShapeInterface value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public ShapeInterface read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + ShapeInterface instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of ShapeInterface given an JSON string + * + * @param jsonString JSON string + * @return An instance of ShapeInterface + * @throws IOException if the JSON string is invalid with respect to ShapeInterface + */ + public static ShapeInterface fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ShapeInterface.class); + } + + /** + * Convert an instance of ShapeInterface to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ShapeOrNull.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ShapeOrNull.java new file mode 100644 index 000000000000..f0d8526c0b84 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/ShapeOrNull.java @@ -0,0 +1,411 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class ShapeOrNull extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ShapeOrNull.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the ShapeOrNull instance itself + */ + public ShapeOrNull putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(ShapeOrNull instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(ShapeOrNull value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 ShapeOrNull + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("shapeType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'shapeType' is missing."); + } + String discriminatorValue = jsonObject.get("shapeType").getAsString(); + if ("Quadrilateral".equals(discriminatorValue)) { + Quadrilateral.validateJsonElement(jsonElement); + return; + } + if ("Triangle".equals(discriminatorValue)) { + Triangle.validateJsonElement(jsonElement); + return; + } + // deserialize Triangle + try { + // validate the JSON object to see if any exception is thrown + Triangle.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage())); + } + + // deserialize Quadrilateral + try { + // validate the JSON object to see if any exception is thrown + Quadrilateral.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for ShapeOrNull: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ShapeOrNull.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ShapeOrNull' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class)); + final TypeAdapter adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ShapeOrNull value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Triangle` + if (value.getActualInstance() instanceof Triangle) { + element = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()); + } + // check if the actual instance is of the type `Quadrilateral` + if (value.getActualInstance() instanceof Quadrilateral) { + element = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public ShapeOrNull read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("shapeType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'shapeType' is missing."); + } + String discriminatorValue = jsonObject.get("shapeType").getAsString(); + if ("Quadrilateral".equals(discriminatorValue)) { + deserialized = adapterQuadrilateral.fromJsonTree(jsonElement); + ShapeOrNull ret = new ShapeOrNull(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("Triangle".equals(discriminatorValue)) { + deserialized = adapterTriangle.fromJsonTree(jsonElement); + ShapeOrNull ret = new ShapeOrNull(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Triangle + try { + // validate the JSON object to see if any exception is thrown + Triangle.validateJsonElement(jsonElement); + actualAdapter = adapterTriangle; + match++; + log.log(Level.FINER, "Input data matches schema 'Triangle'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); + } + + // deserialize Quadrilateral + try { + // validate the JSON object to see if any exception is thrown + Quadrilateral.validateJsonElement(jsonElement); + actualAdapter = adapterQuadrilateral; + match++; + log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); + } + + if (match == 1) { + ShapeOrNull ret = new ShapeOrNull(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for ShapeOrNull: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public ShapeOrNull() { + super("oneOf", Boolean.TRUE); + } + + public ShapeOrNull(Triangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public ShapeOrNull(Quadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Triangle", Triangle.class); + schemas.put("Quadrilateral", Quadrilateral.class); + } + + @Override + public Map> getSchemas() { + return ShapeOrNull.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Quadrilateral, Triangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Triangle.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(Quadrilateral.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); + } + + /** + * Get the actual instance, which can be the following: + * Quadrilateral, Triangle + * + * @return The actual instance (Quadrilateral, Triangle) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Triangle` + * @throws ClassCastException if the instance is not `Triangle` + */ + @SuppressWarnings("unchecked") + public Triangle getTriangle() throws ClassCastException { + return (Triangle)super.getActualInstance(); + } + + /** + * Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Quadrilateral` + * @throws ClassCastException if the instance is not `Quadrilateral` + */ + @SuppressWarnings("unchecked") + public Quadrilateral getQuadrilateral() throws ClassCastException { + return (Quadrilateral)super.getActualInstance(); + } + + + + /** + * Create an instance of ShapeOrNull given an JSON string + * + * @param jsonString JSON string + * @return An instance of ShapeOrNull + * @throws IOException if the JSON string is invalid with respect to ShapeOrNull + */ + public static ShapeOrNull fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, ShapeOrNull.class); + } + + /** + * Convert an instance of ShapeOrNull to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java new file mode 100644 index 000000000000..97bb1c60bacd --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java @@ -0,0 +1,313 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * SimpleQuadrilateral + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class SimpleQuadrilateral { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + @javax.annotation.Nonnull + private String shapeType; + + public static final String SERIALIZED_NAME_QUADRILATERAL_TYPE = "quadrilateralType"; + @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) + @javax.annotation.Nonnull + private String quadrilateralType; + + public SimpleQuadrilateral() { + } + + public SimpleQuadrilateral shapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + */ + @javax.annotation.Nonnull + + public String getShapeType() { + return shapeType; + } + + public void setShapeType(@javax.annotation.Nonnull String shapeType) { + this.shapeType = shapeType; + } + + + public SimpleQuadrilateral quadrilateralType(@javax.annotation.Nonnull String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + return this; + } + + /** + * Get quadrilateralType + * @return quadrilateralType + */ + @javax.annotation.Nonnull + + public String getQuadrilateralType() { + return quadrilateralType; + } + + public void setQuadrilateralType(@javax.annotation.Nonnull String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the SimpleQuadrilateral instance itself + */ + public SimpleQuadrilateral putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SimpleQuadrilateral simpleQuadrilateral = (SimpleQuadrilateral) o; + return Objects.equals(this.shapeType, simpleQuadrilateral.shapeType) && + Objects.equals(this.quadrilateralType, simpleQuadrilateral.quadrilateralType)&& + Objects.equals(this.additionalProperties, simpleQuadrilateral.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, quadrilateralType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SimpleQuadrilateral {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("shapeType", "quadrilateralType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("shapeType", "quadrilateralType")); + } + + /** + * 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 SimpleQuadrilateral + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!SimpleQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in SimpleQuadrilateral is not found in the empty JSON string", SimpleQuadrilateral.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : SimpleQuadrilateral.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("shapeType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString())); + } + if (!jsonObj.get("quadrilateralType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `quadrilateralType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("quadrilateralType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!SimpleQuadrilateral.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'SimpleQuadrilateral' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(SimpleQuadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, SimpleQuadrilateral value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public SimpleQuadrilateral read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + SimpleQuadrilateral instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of SimpleQuadrilateral given an JSON string + * + * @param jsonString JSON string + * @return An instance of SimpleQuadrilateral + * @throws IOException if the JSON string is invalid with respect to SimpleQuadrilateral + */ + public static SimpleQuadrilateral fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, SimpleQuadrilateral.class); + } + + /** + * Convert an instance of SimpleQuadrilateral to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/SpecialModelName.java new file mode 100644 index 000000000000..9ca16d7b982b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -0,0 +1,303 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * SpecialModelName + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class SpecialModelName { + public static final String SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; + @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) + @javax.annotation.Nullable + private Long $specialPropertyName; + + public static final String SERIALIZED_NAME_SPECIAL_MODEL_NAME = "_special_model.name_"; + @SerializedName(SERIALIZED_NAME_SPECIAL_MODEL_NAME) + @javax.annotation.Nullable + private String specialModelName; + + public SpecialModelName() { + } + + public SpecialModelName $specialPropertyName(@javax.annotation.Nullable Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + return this; + } + + /** + * Get $specialPropertyName + * @return $specialPropertyName + */ + @javax.annotation.Nullable + + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + public void set$SpecialPropertyName(@javax.annotation.Nullable Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + + public SpecialModelName specialModelName(@javax.annotation.Nullable String specialModelName) { + this.specialModelName = specialModelName; + return this; + } + + /** + * Get specialModelName + * @return specialModelName + */ + @javax.annotation.Nullable + + public String getSpecialModelName() { + return specialModelName; + } + + public void setSpecialModelName(@javax.annotation.Nullable String specialModelName) { + this.specialModelName = specialModelName; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the SpecialModelName instance itself + */ + public SpecialModelName putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.$specialPropertyName, specialModelName.$specialPropertyName) && + Objects.equals(this.specialModelName, specialModelName.specialModelName)&& + Objects.equals(this.additionalProperties, specialModelName.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash($specialPropertyName, specialModelName, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); + sb.append(" specialModelName: ").append(toIndentedString(specialModelName)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("$special[property.name]", "_special_model.name_")); + + // 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 SpecialModelName + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!SpecialModelName.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in SpecialModelName is not found in the empty JSON string", SpecialModelName.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("_special_model.name_") != null && !jsonObj.get("_special_model.name_").isJsonNull()) && !jsonObj.get("_special_model.name_").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `_special_model.name_` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_special_model.name_").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!SpecialModelName.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'SpecialModelName' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(SpecialModelName.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, SpecialModelName value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public SpecialModelName read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + SpecialModelName instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of SpecialModelName given an JSON string + * + * @param jsonString JSON string + * @return An instance of SpecialModelName + * @throws IOException if the JSON string is invalid with respect to SpecialModelName + */ + public static SpecialModelName fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, SpecialModelName.class); + } + + /** + * Convert an instance of SpecialModelName to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 000000000000..e26547d495ae --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,303 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Tag + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Tag { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nullable + private String name; + + public Tag() { + } + + public Tag id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public Tag name(@javax.annotation.Nullable String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nullable + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nullable String name) { + this.name = name; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Tag instance itself + */ + public Tag putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name)&& + Objects.equals(this.additionalProperties, tag.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "name")); + + // 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 Tag + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Tag is not found in the empty JSON string", Tag.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Tag.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Tag' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Tag.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Tag value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Tag read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Tag instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Tag given an JSON string + * + * @param jsonString JSON string + * @return An instance of Tag + * @throws IOException if the JSON string is invalid with respect to Tag + */ + public static Tag fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Tag.class); + } + + /** + * Convert an instance of Tag to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java new file mode 100644 index 000000000000..93951b2429ab --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java @@ -0,0 +1,276 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * TestInlineFreeformAdditionalPropertiesRequest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class TestInlineFreeformAdditionalPropertiesRequest { + public static final String SERIALIZED_NAME_SOME_PROPERTY = "someProperty"; + @SerializedName(SERIALIZED_NAME_SOME_PROPERTY) + @javax.annotation.Nullable + private String someProperty; + + public TestInlineFreeformAdditionalPropertiesRequest() { + } + + public TestInlineFreeformAdditionalPropertiesRequest someProperty(@javax.annotation.Nullable String someProperty) { + this.someProperty = someProperty; + return this; + } + + /** + * Get someProperty + * @return someProperty + */ + @javax.annotation.Nullable + + public String getSomeProperty() { + return someProperty; + } + + public void setSomeProperty(@javax.annotation.Nullable String someProperty) { + this.someProperty = someProperty; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the TestInlineFreeformAdditionalPropertiesRequest instance itself + */ + public TestInlineFreeformAdditionalPropertiesRequest putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = (TestInlineFreeformAdditionalPropertiesRequest) o; + return Objects.equals(this.someProperty, testInlineFreeformAdditionalPropertiesRequest.someProperty)&& + Objects.equals(this.additionalProperties, testInlineFreeformAdditionalPropertiesRequest.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(someProperty, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); + sb.append(" someProperty: ").append(toIndentedString(someProperty)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("someProperty")); + + // 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 TestInlineFreeformAdditionalPropertiesRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!TestInlineFreeformAdditionalPropertiesRequest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in TestInlineFreeformAdditionalPropertiesRequest is not found in the empty JSON string", TestInlineFreeformAdditionalPropertiesRequest.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("someProperty") != null && !jsonObj.get("someProperty").isJsonNull()) && !jsonObj.get("someProperty").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `someProperty` to be a primitive type in the JSON string but got `%s`", jsonObj.get("someProperty").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!TestInlineFreeformAdditionalPropertiesRequest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'TestInlineFreeformAdditionalPropertiesRequest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(TestInlineFreeformAdditionalPropertiesRequest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, TestInlineFreeformAdditionalPropertiesRequest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public TestInlineFreeformAdditionalPropertiesRequest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + TestInlineFreeformAdditionalPropertiesRequest instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of TestInlineFreeformAdditionalPropertiesRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of TestInlineFreeformAdditionalPropertiesRequest + * @throws IOException if the JSON string is invalid with respect to TestInlineFreeformAdditionalPropertiesRequest + */ + public static TestInlineFreeformAdditionalPropertiesRequest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, TestInlineFreeformAdditionalPropertiesRequest.class); + } + + /** + * Convert an instance of TestInlineFreeformAdditionalPropertiesRequest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Triangle.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Triangle.java new file mode 100644 index 000000000000..2986713c8592 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Triangle.java @@ -0,0 +1,468 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Triangle extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Triangle.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Triangle instance itself + */ + public Triangle putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(Triangle instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(Triangle value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 Triangle + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("triangleType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'triangleType' is missing."); + } + String discriminatorValue = jsonObject.get("triangleType").getAsString(); + if ("EquilateralTriangle".equals(discriminatorValue)) { + EquilateralTriangle.validateJsonElement(jsonElement); + return; + } + if ("IsoscelesTriangle".equals(discriminatorValue)) { + IsoscelesTriangle.validateJsonElement(jsonElement); + return; + } + if ("ScaleneTriangle".equals(discriminatorValue)) { + ScaleneTriangle.validateJsonElement(jsonElement); + return; + } + // deserialize EquilateralTriangle + try { + // validate the JSON object to see if any exception is thrown + EquilateralTriangle.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for EquilateralTriangle failed with `%s`.", e.getMessage())); + } + + // deserialize IsoscelesTriangle + try { + // validate the JSON object to see if any exception is thrown + IsoscelesTriangle.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for IsoscelesTriangle failed with `%s`.", e.getMessage())); + } + + // deserialize ScaleneTriangle + try { + // validate the JSON object to see if any exception is thrown + ScaleneTriangle.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for ScaleneTriangle failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Triangle: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Triangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Triangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterEquilateralTriangle = gson.getDelegateAdapter(this, TypeToken.get(EquilateralTriangle.class)); + final TypeAdapter adapterIsoscelesTriangle = gson.getDelegateAdapter(this, TypeToken.get(IsoscelesTriangle.class)); + final TypeAdapter adapterScaleneTriangle = gson.getDelegateAdapter(this, TypeToken.get(ScaleneTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Triangle value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `EquilateralTriangle` + if (value.getActualInstance() instanceof EquilateralTriangle) { + element = adapterEquilateralTriangle.toJsonTree((EquilateralTriangle)value.getActualInstance()); + } + // check if the actual instance is of the type `IsoscelesTriangle` + if (value.getActualInstance() instanceof IsoscelesTriangle) { + element = adapterIsoscelesTriangle.toJsonTree((IsoscelesTriangle)value.getActualInstance()); + } + // check if the actual instance is of the type `ScaleneTriangle` + if (value.getActualInstance() instanceof ScaleneTriangle) { + element = adapterScaleneTriangle.toJsonTree((ScaleneTriangle)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public Triangle read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + JsonObject jsonObject = jsonElement.getAsJsonObject(); + if (jsonObject.get("triangleType") == null) { + throw new IOException("Failed to deserialize as the discriminator field 'triangleType' is missing."); + } + String discriminatorValue = jsonObject.get("triangleType").getAsString(); + if ("EquilateralTriangle".equals(discriminatorValue)) { + deserialized = adapterEquilateralTriangle.fromJsonTree(jsonElement); + Triangle ret = new Triangle(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("IsoscelesTriangle".equals(discriminatorValue)) { + deserialized = adapterIsoscelesTriangle.fromJsonTree(jsonElement); + Triangle ret = new Triangle(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + if ("ScaleneTriangle".equals(discriminatorValue)) { + deserialized = adapterScaleneTriangle.fromJsonTree(jsonElement); + Triangle ret = new Triangle(); + ret.setActualInstance(deserialized); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize EquilateralTriangle + try { + // validate the JSON object to see if any exception is thrown + EquilateralTriangle.validateJsonElement(jsonElement); + actualAdapter = adapterEquilateralTriangle; + match++; + log.log(Level.FINER, "Input data matches schema 'EquilateralTriangle'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for EquilateralTriangle failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'EquilateralTriangle'", e); + } + + // deserialize IsoscelesTriangle + try { + // validate the JSON object to see if any exception is thrown + IsoscelesTriangle.validateJsonElement(jsonElement); + actualAdapter = adapterIsoscelesTriangle; + match++; + log.log(Level.FINER, "Input data matches schema 'IsoscelesTriangle'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for IsoscelesTriangle failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'IsoscelesTriangle'", e); + } + + // deserialize ScaleneTriangle + try { + // validate the JSON object to see if any exception is thrown + ScaleneTriangle.validateJsonElement(jsonElement); + actualAdapter = adapterScaleneTriangle; + match++; + log.log(Level.FINER, "Input data matches schema 'ScaleneTriangle'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for ScaleneTriangle failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'ScaleneTriangle'", e); + } + + if (match == 1) { + Triangle ret = new Triangle(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Triangle: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Triangle() { + super("oneOf", Boolean.FALSE); + } + + public Triangle(EquilateralTriangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Triangle(IsoscelesTriangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Triangle(ScaleneTriangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("EquilateralTriangle", EquilateralTriangle.class); + schemas.put("IsoscelesTriangle", IsoscelesTriangle.class); + schemas.put("ScaleneTriangle", ScaleneTriangle.class); + } + + @Override + public Map> getSchemas() { + return Triangle.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(EquilateralTriangle.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(IsoscelesTriangle.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(ScaleneTriangle.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle"); + } + + /** + * Get the actual instance, which can be the following: + * EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle + * + * @return The actual instance (EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `EquilateralTriangle`. If the actual instance is not `EquilateralTriangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `EquilateralTriangle` + * @throws ClassCastException if the instance is not `EquilateralTriangle` + */ + @SuppressWarnings("unchecked") + public EquilateralTriangle getEquilateralTriangle() throws ClassCastException { + return (EquilateralTriangle)super.getActualInstance(); + } + + /** + * Get the actual instance of `IsoscelesTriangle`. If the actual instance is not `IsoscelesTriangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `IsoscelesTriangle` + * @throws ClassCastException if the instance is not `IsoscelesTriangle` + */ + @SuppressWarnings("unchecked") + public IsoscelesTriangle getIsoscelesTriangle() throws ClassCastException { + return (IsoscelesTriangle)super.getActualInstance(); + } + + /** + * Get the actual instance of `ScaleneTriangle`. If the actual instance is not `ScaleneTriangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `ScaleneTriangle` + * @throws ClassCastException if the instance is not `ScaleneTriangle` + */ + @SuppressWarnings("unchecked") + public ScaleneTriangle getScaleneTriangle() throws ClassCastException { + return (ScaleneTriangle)super.getActualInstance(); + } + + + + /** + * Create an instance of Triangle given an JSON string + * + * @param jsonString JSON string + * @return An instance of Triangle + * @throws IOException if the JSON string is invalid with respect to Triangle + */ + public static Triangle fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Triangle.class); + } + + /** + * Convert an instance of Triangle to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/TriangleInterface.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/TriangleInterface.java new file mode 100644 index 000000000000..924ed2e39819 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/TriangleInterface.java @@ -0,0 +1,283 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * TriangleInterface + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class TriangleInterface { + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + @javax.annotation.Nonnull + private String triangleType; + + public TriangleInterface() { + } + + public TriangleInterface triangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + */ + @javax.annotation.Nonnull + + public String getTriangleType() { + return triangleType; + } + + public void setTriangleType(@javax.annotation.Nonnull String triangleType) { + this.triangleType = triangleType; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the TriangleInterface instance itself + */ + public TriangleInterface putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TriangleInterface triangleInterface = (TriangleInterface) o; + return Objects.equals(this.triangleType, triangleInterface.triangleType)&& + Objects.equals(this.additionalProperties, triangleInterface.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(triangleType, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TriangleInterface {\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("triangleType")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("triangleType")); + } + + /** + * 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 TriangleInterface + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!TriangleInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in TriangleInterface is not found in the empty JSON string", TriangleInterface.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : TriangleInterface.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("triangleType").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!TriangleInterface.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'TriangleInterface' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(TriangleInterface.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, TriangleInterface value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public TriangleInterface read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + TriangleInterface instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of TriangleInterface given an JSON string + * + * @param jsonString JSON string + * @return An instance of TriangleInterface + * @throws IOException if the JSON string is invalid with respect to TriangleInterface + */ + public static TriangleInterface fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, TriangleInterface.class); + } + + /** + * Convert an instance of TriangleInterface to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/User.java new file mode 100644 index 000000000000..3629ea7318c7 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/User.java @@ -0,0 +1,588 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * User + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class User { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + @javax.annotation.Nullable + private Long id; + + public static final String SERIALIZED_NAME_USERNAME = "username"; + @SerializedName(SERIALIZED_NAME_USERNAME) + @javax.annotation.Nullable + private String username; + + public static final String SERIALIZED_NAME_FIRST_NAME = "firstName"; + @SerializedName(SERIALIZED_NAME_FIRST_NAME) + @javax.annotation.Nullable + private String firstName; + + public static final String SERIALIZED_NAME_LAST_NAME = "lastName"; + @SerializedName(SERIALIZED_NAME_LAST_NAME) + @javax.annotation.Nullable + private String lastName; + + public static final String SERIALIZED_NAME_EMAIL = "email"; + @SerializedName(SERIALIZED_NAME_EMAIL) + @javax.annotation.Nullable + private String email; + + public static final String SERIALIZED_NAME_PASSWORD = "password"; + @SerializedName(SERIALIZED_NAME_PASSWORD) + @javax.annotation.Nullable + private String password; + + public static final String SERIALIZED_NAME_PHONE = "phone"; + @SerializedName(SERIALIZED_NAME_PHONE) + @javax.annotation.Nullable + private String phone; + + public static final String SERIALIZED_NAME_USER_STATUS = "userStatus"; + @SerializedName(SERIALIZED_NAME_USER_STATUS) + @javax.annotation.Nullable + private Integer userStatus; + + public static final String SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS = "objectWithNoDeclaredProps"; + @SerializedName(SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS) + @javax.annotation.Nullable + private Object objectWithNoDeclaredProps; + + public static final String SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE = "objectWithNoDeclaredPropsNullable"; + @SerializedName(SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE) + @javax.annotation.Nullable + private Object objectWithNoDeclaredPropsNullable; + + public static final String SERIALIZED_NAME_ANY_TYPE_PROP = "anyTypeProp"; + @SerializedName(SERIALIZED_NAME_ANY_TYPE_PROP) + @javax.annotation.Nullable + private Object anyTypeProp = null; + + public static final String SERIALIZED_NAME_ANY_TYPE_PROP_NULLABLE = "anyTypePropNullable"; + @SerializedName(SERIALIZED_NAME_ANY_TYPE_PROP_NULLABLE) + @javax.annotation.Nullable + private Object anyTypePropNullable = null; + + public User() { + } + + public User id(@javax.annotation.Nullable Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + @javax.annotation.Nullable + + public Long getId() { + return id; + } + + public void setId(@javax.annotation.Nullable Long id) { + this.id = id; + } + + + public User username(@javax.annotation.Nullable String username) { + this.username = username; + return this; + } + + /** + * Get username + * @return username + */ + @javax.annotation.Nullable + + public String getUsername() { + return username; + } + + public void setUsername(@javax.annotation.Nullable String username) { + this.username = username; + } + + + public User firstName(@javax.annotation.Nullable String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + */ + @javax.annotation.Nullable + + public String getFirstName() { + return firstName; + } + + public void setFirstName(@javax.annotation.Nullable String firstName) { + this.firstName = firstName; + } + + + public User lastName(@javax.annotation.Nullable String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + */ + @javax.annotation.Nullable + + public String getLastName() { + return lastName; + } + + public void setLastName(@javax.annotation.Nullable String lastName) { + this.lastName = lastName; + } + + + public User email(@javax.annotation.Nullable String email) { + this.email = email; + return this; + } + + /** + * Get email + * @return email + */ + @javax.annotation.Nullable + + public String getEmail() { + return email; + } + + public void setEmail(@javax.annotation.Nullable String email) { + this.email = email; + } + + + public User password(@javax.annotation.Nullable String password) { + this.password = password; + return this; + } + + /** + * Get password + * @return password + */ + @javax.annotation.Nullable + + public String getPassword() { + return password; + } + + public void setPassword(@javax.annotation.Nullable String password) { + this.password = password; + } + + + public User phone(@javax.annotation.Nullable String phone) { + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + */ + @javax.annotation.Nullable + + public String getPhone() { + return phone; + } + + public void setPhone(@javax.annotation.Nullable String phone) { + this.phone = phone; + } + + + public User userStatus(@javax.annotation.Nullable Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + */ + @javax.annotation.Nullable + + public Integer getUserStatus() { + return userStatus; + } + + public void setUserStatus(@javax.annotation.Nullable Integer userStatus) { + this.userStatus = userStatus; + } + + + public User objectWithNoDeclaredProps(@javax.annotation.Nullable Object objectWithNoDeclaredProps) { + this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; + return this; + } + + /** + * test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + * @return objectWithNoDeclaredProps + */ + @javax.annotation.Nullable + + public Object getObjectWithNoDeclaredProps() { + return objectWithNoDeclaredProps; + } + + public void setObjectWithNoDeclaredProps(@javax.annotation.Nullable Object objectWithNoDeclaredProps) { + this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; + } + + + public User objectWithNoDeclaredPropsNullable(@javax.annotation.Nullable Object objectWithNoDeclaredPropsNullable) { + this.objectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + return this; + } + + /** + * test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + * @return objectWithNoDeclaredPropsNullable + */ + @javax.annotation.Nullable + + public Object getObjectWithNoDeclaredPropsNullable() { + return objectWithNoDeclaredPropsNullable; + } + + public void setObjectWithNoDeclaredPropsNullable(@javax.annotation.Nullable Object objectWithNoDeclaredPropsNullable) { + this.objectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + } + + + public User anyTypeProp(@javax.annotation.Nullable Object anyTypeProp) { + this.anyTypeProp = anyTypeProp; + return this; + } + + /** + * test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + * @return anyTypeProp + */ + @javax.annotation.Nullable + + public Object getAnyTypeProp() { + return anyTypeProp; + } + + public void setAnyTypeProp(@javax.annotation.Nullable Object anyTypeProp) { + this.anyTypeProp = anyTypeProp; + } + + + public User anyTypePropNullable(@javax.annotation.Nullable Object anyTypePropNullable) { + this.anyTypePropNullable = anyTypePropNullable; + return this; + } + + /** + * test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + * @return anyTypePropNullable + */ + @javax.annotation.Nullable + + public Object getAnyTypePropNullable() { + return anyTypePropNullable; + } + + public void setAnyTypePropNullable(@javax.annotation.Nullable Object anyTypePropNullable) { + this.anyTypePropNullable = anyTypePropNullable; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the User instance itself + */ + public User putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus) && + Objects.equals(this.objectWithNoDeclaredProps, user.objectWithNoDeclaredProps) && + Objects.equals(this.objectWithNoDeclaredPropsNullable, user.objectWithNoDeclaredPropsNullable) && + Objects.equals(this.anyTypeProp, user.anyTypeProp) && + Objects.equals(this.anyTypePropNullable, user.anyTypePropNullable)&& + Objects.equals(this.additionalProperties, user.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, anyTypeProp, anyTypePropNullable, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append(" objectWithNoDeclaredProps: ").append(toIndentedString(objectWithNoDeclaredProps)).append("\n"); + sb.append(" objectWithNoDeclaredPropsNullable: ").append(toIndentedString(objectWithNoDeclaredPropsNullable)).append("\n"); + sb.append(" anyTypeProp: ").append(toIndentedString(anyTypeProp)).append("\n"); + sb.append(" anyTypePropNullable: ").append(toIndentedString(anyTypePropNullable)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("id", "username", "firstName", "lastName", "email", "password", "phone", "userStatus", "objectWithNoDeclaredProps", "objectWithNoDeclaredPropsNullable", "anyTypeProp", "anyTypePropNullable")); + + // 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 User + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString())); + } + if ((jsonObj.get("firstName") != null && !jsonObj.get("firstName").isJsonNull()) && !jsonObj.get("firstName").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `firstName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("firstName").toString())); + } + if ((jsonObj.get("lastName") != null && !jsonObj.get("lastName").isJsonNull()) && !jsonObj.get("lastName").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `lastName` to be a primitive type in the JSON string but got `%s`", jsonObj.get("lastName").toString())); + } + if ((jsonObj.get("email") != null && !jsonObj.get("email").isJsonNull()) && !jsonObj.get("email").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `email` to be a primitive type in the JSON string but got `%s`", jsonObj.get("email").toString())); + } + if ((jsonObj.get("password") != null && !jsonObj.get("password").isJsonNull()) && !jsonObj.get("password").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `password` to be a primitive type in the JSON string but got `%s`", jsonObj.get("password").toString())); + } + if ((jsonObj.get("phone") != null && !jsonObj.get("phone").isJsonNull()) && !jsonObj.get("phone").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `phone` to be a primitive type in the JSON string but got `%s`", jsonObj.get("phone").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!User.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'User' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(User.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, User value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public User read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + User instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of User given an JSON string + * + * @param jsonString JSON string + * @return An instance of User + * @throws IOException if the JSON string is invalid with respect to User + */ + public static User fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, User.class); + } + + /** + * Convert an instance of User to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Value.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Value.java new file mode 100644 index 000000000000..a1b64f343c6d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Value.java @@ -0,0 +1,385 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; + +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Value extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Value.class.getName()); + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Value instance itself + */ + public Value putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + /** + * Record the properties that the matched oneOf schema did not consume. + * + *

The wrapper only owns what the selected child schema left behind. When that child accepts + * additional properties itself it absorbs them all and this records nothing, so a property is + * never stored — and therefore never written — twice.

+ */ + private static void collectUnconsumedProperties(Value instance, JsonElement jsonElement, Gson gson) { + if (jsonElement == null || !jsonElement.isJsonObject() || instance.getActualInstance() == null) { + return; + } + JsonElement consumedElement = gson.toJsonTree(instance.getActualInstance()); + if (consumedElement == null || !consumedElement.isJsonObject()) { + return; + } + JsonObject consumed = consumedElement.getAsJsonObject(); + for (Map.Entry entry : jsonElement.getAsJsonObject().entrySet()) { + if (consumed.has(entry.getKey())) { + continue; + } + JsonElement value = entry.getValue(); + if (value.isJsonPrimitive()) { + JsonPrimitive primitive = value.getAsJsonPrimitive(); + if (primitive.isString()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsString()); + } else if (primitive.isNumber()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsNumber()); + } else if (primitive.isBoolean()) { + instance.putAdditionalProperty(entry.getKey(), primitive.getAsBoolean()); + } + } else if (value.isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, List.class)); + } else if (value.isJsonObject()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(value, HashMap.class)); + } + } + } + + /** + * Merge the unconsumed properties back into the JSON produced by the matched oneOf schema. + */ + private static void writeUnconsumedProperties(Value value, JsonObject obj, Gson gson) { + if (value.getAdditionalProperties() == null) { + return; + } + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (obj.has(entry.getKey())) { + // the child schema owns this property + continue; + } + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue())); + } + } + + /** + * 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 Value + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + int matches = 0; + List errorMessages = new ArrayList<>(); + // deserialize Scalar + try { + // validate the JSON object to see if any exception is thrown + Scalar.validateJsonElement(jsonElement); + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Scalar failed with `%s`.", e.getMessage())); + } + + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + Scalar.validateJsonElement(element); + } + matches++; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + } + + if (matches != 1) { + throw new IOException(String.format("Failed deserialization for Value: %d classes match result, expected 1. %s", matches, errorMessages)); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Value.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Value' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterScalar = gson.getDelegateAdapter(this, TypeToken.get(Scalar.class)); + final Type typeInstanceListScalar = new TypeToken>(){}.getType(); + final TypeAdapter> adapterListScalar = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstanceListScalar)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Value value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + JsonElement element = null; + // check if the actual instance is of the type `Scalar` + if (value.getActualInstance() instanceof Scalar) { + element = adapterScalar.toJsonTree((Scalar)value.getActualInstance()); + } + // check if the actual instance is of the type `List` + if (value.getActualInstance() instanceof List) { + element = adapterListScalar.toJsonTree((List)value.getActualInstance()); + } + + if (element == null) { + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: List, Scalar"); + } + + if (element.isJsonObject()) { + writeUnconsumedProperties(value, element.getAsJsonObject(), gson); + } + elementAdapter.write(out, element); + } + + @Override + public Value read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = null; + + // deserialize Scalar + try { + // validate the JSON object to see if any exception is thrown + Scalar.validateJsonElement(jsonElement); + actualAdapter = adapterScalar; + match++; + log.log(Level.FINER, "Input data matches schema 'Scalar'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Scalar failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Scalar'", e); + } + + // deserialize List + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); + } + for (JsonElement element : jsonElement.getAsJsonArray()) { + Scalar.validateJsonElement(element); + } + actualAdapter = adapterListScalar; + match++; + log.log(Level.FINER, "Input data matches schema 'List'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for List failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'List'", e); + } + + if (match == 1) { + Value ret = new Value(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + collectUnconsumedProperties(ret, jsonElement, gson); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Value: %d classes match result, expected 1. %s", match, errorMessages)); + } + }.nullSafe(); + } + } + + + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap<>(); + + public Value() { + super("oneOf", Boolean.FALSE); + } + + public Value(Scalar o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Value(List o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Scalar", Scalar.class); + schemas.put("List", List.class); + } + + @Override + public Map> getSchemas() { + return Value.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * List, Scalar + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (JSON.isInstanceOf(Scalar.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + if (JSON.isInstanceOf(List.class, instance, new HashSet>())) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be List, Scalar"); + } + + /** + * Get the actual instance, which can be the following: + * List, Scalar + * + * @return The actual instance (List, Scalar) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Scalar`. If the actual instance is not `Scalar`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Scalar` + * @throws ClassCastException if the instance is not `Scalar` + */ + @SuppressWarnings("unchecked") + public Scalar getScalar() throws ClassCastException { + return (Scalar)super.getActualInstance(); + } + + /** + * Get the actual instance of `List`. If the actual instance is not `List`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `List` + * @throws ClassCastException if the instance is not `List` + */ + @SuppressWarnings("unchecked") + public List getListScalar() throws ClassCastException { + return (List)super.getActualInstance(); + } + + + + /** + * Create an instance of Value given an JSON string + * + * @param jsonString JSON string + * @return An instance of Value + * @throws IOException if the JSON string is invalid with respect to Value + */ + public static Value fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Value.class); + } + + /** + * Convert an instance of Value to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Variable.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Variable.java new file mode 100644 index 000000000000..31ef0cd89e9a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Variable.java @@ -0,0 +1,312 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Value object + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Variable { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + @javax.annotation.Nonnull + private String name; + + public static final String SERIALIZED_NAME_VALUE = "value"; + @SerializedName(SERIALIZED_NAME_VALUE) + @javax.annotation.Nonnull + private Value value; + + public Variable() { + } + + public Variable name(@javax.annotation.Nonnull String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @javax.annotation.Nonnull + + public String getName() { + return name; + } + + public void setName(@javax.annotation.Nonnull String name) { + this.name = name; + } + + + public Variable value(@javax.annotation.Nonnull Value value) { + this.value = value; + return this; + } + + /** + * Get value + * @return value + */ + @javax.annotation.Nonnull + + public Value getValue() { + return value; + } + + public void setValue(@javax.annotation.Nonnull Value value) { + this.value = value; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Variable instance itself + */ + public Variable putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Variable variable = (Variable) o; + return Objects.equals(this.name, variable.name) && + Objects.equals(this.value, variable.value)&& + Objects.equals(this.additionalProperties, variable.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(name, value, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Variable {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("name", "value")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("name", "value")); + } + + /** + * 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 Variable + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Variable.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Variable is not found in the empty JSON string", Variable.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Variable.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // validate the required field `value` + Value.validateJsonElement(jsonObj.get("value")); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Variable.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Variable' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Variable.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Variable value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Variable read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Variable instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Variable given an JSON string + * + * @param jsonString JSON string + * @return An instance of Variable + * @throws IOException if the JSON string is invalid with respect to Variable + */ + public static Variable fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Variable.class); + } + + /** + * Convert an instance of Variable to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Whale.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Whale.java new file mode 100644 index 000000000000..89ae72af90a3 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Whale.java @@ -0,0 +1,337 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Whale + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Whale { + public static final String SERIALIZED_NAME_HAS_BALEEN = "hasBaleen"; + @SerializedName(SERIALIZED_NAME_HAS_BALEEN) + @javax.annotation.Nullable + private Boolean hasBaleen; + + public static final String SERIALIZED_NAME_HAS_TEETH = "hasTeeth"; + @SerializedName(SERIALIZED_NAME_HAS_TEETH) + @javax.annotation.Nullable + private Boolean hasTeeth; + + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + @javax.annotation.Nonnull + private String className; + + public Whale() { + } + + public Whale hasBaleen(@javax.annotation.Nullable Boolean hasBaleen) { + this.hasBaleen = hasBaleen; + return this; + } + + /** + * Get hasBaleen + * @return hasBaleen + */ + @javax.annotation.Nullable + + public Boolean getHasBaleen() { + return hasBaleen; + } + + public void setHasBaleen(@javax.annotation.Nullable Boolean hasBaleen) { + this.hasBaleen = hasBaleen; + } + + + public Whale hasTeeth(@javax.annotation.Nullable Boolean hasTeeth) { + this.hasTeeth = hasTeeth; + return this; + } + + /** + * Get hasTeeth + * @return hasTeeth + */ + @javax.annotation.Nullable + + public Boolean getHasTeeth() { + return hasTeeth; + } + + public void setHasTeeth(@javax.annotation.Nullable Boolean hasTeeth) { + this.hasTeeth = hasTeeth; + } + + + public Whale className(@javax.annotation.Nonnull String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + */ + @javax.annotation.Nonnull + + public String getClassName() { + return className; + } + + public void setClassName(@javax.annotation.Nonnull String className) { + this.className = className; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Whale instance itself + */ + public Whale putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Whale whale = (Whale) o; + return Objects.equals(this.hasBaleen, whale.hasBaleen) && + Objects.equals(this.hasTeeth, whale.hasTeeth) && + Objects.equals(this.className, whale.className)&& + Objects.equals(this.additionalProperties, whale.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(hasBaleen, hasTeeth, className, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Whale {\n"); + sb.append(" hasBaleen: ").append(toIndentedString(hasBaleen)).append("\n"); + sb.append(" hasTeeth: ").append(toIndentedString(hasTeeth)).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("hasBaleen", "hasTeeth", "className")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("className")); + } + + /** + * 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 Whale + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Whale.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Whale is not found in the empty JSON string", Whale.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Whale.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("className").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Whale.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Whale' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Whale.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Whale value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Whale read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Whale instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Whale given an JSON string + * + * @param jsonString JSON string + * @return An instance of Whale + * @throws IOException if the JSON string is invalid with respect to Whale + */ + public static Whale fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Whale.class); + } + + /** + * Convert an instance of Whale to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Zebra.java b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Zebra.java new file mode 100644 index 000000000000..098f587f4b86 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/main/java/org/openapitools/client/model/Zebra.java @@ -0,0 +1,372 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.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 java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import java.util.HashSet; + +import org.openapitools.client.JSON; + +/** + * Zebra + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.28.0-SNAPSHOT") +public class Zebra { + /** + * Gets or Sets type + */ + @JsonAdapter(TypeEnum.Adapter.class) + public enum TypeEnum { + PLAINS("plains"), + + MOUNTAIN("mountain"), + + GREVYS("grevys"); + + private String value; + + TypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static TypeEnum fromValue(String value) { + for (TypeEnum b : TypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final TypeEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public TypeEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return TypeEnum.fromValue(value); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + TypeEnum.fromValue(value); + } + } + + public static final String SERIALIZED_NAME_TYPE = "type"; + @SerializedName(SERIALIZED_NAME_TYPE) + @javax.annotation.Nullable + private TypeEnum type; + + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + @javax.annotation.Nonnull + private String className; + + public Zebra() { + } + + public Zebra type(@javax.annotation.Nullable TypeEnum type) { + this.type = type; + return this; + } + + /** + * Get type + * @return type + */ + @javax.annotation.Nullable + + public TypeEnum getType() { + return type; + } + + public void setType(@javax.annotation.Nullable TypeEnum type) { + this.type = type; + } + + + public Zebra className(@javax.annotation.Nonnull String className) { + this.className = className; + return this; + } + + /** + * Get className + * @return className + */ + @javax.annotation.Nonnull + + public String getClassName() { + return className; + } + + public void setClassName(@javax.annotation.Nonnull String className) { + this.className = className; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the Zebra instance itself + */ + public Zebra putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Zebra zebra = (Zebra) o; + return Objects.equals(this.type, zebra.type) && + Objects.equals(this.className, zebra.className)&& + Objects.equals(this.additionalProperties, zebra.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(type, className, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Zebra {\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).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) { + return o == null ? "null" : 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("type", "className")); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(Arrays.asList("className")); + } + + /** + * 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 Zebra + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!Zebra.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field(s) %s in Zebra is not found in the empty JSON string", Zebra.openapiRequiredFields.toString())); + } + return; // nothing else to validate in an empty JSON string + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Zebra.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); + } + // validate the optional field `type` + if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) { + TypeEnum.validateJsonElement(jsonObj.get("type")); + } + if (!jsonObj.get("className").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Zebra.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Zebra' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Zebra.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Zebra value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonNull()) { + obj.add(entry.getKey(), com.google.gson.JsonNull.INSTANCE); + } else if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public Zebra read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + Zebra instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format(java.util.Locale.ROOT, "The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of Zebra given an JSON string + * + * @param jsonString JSON string + * @return An instance of Zebra + * @throws IOException if the JSON string is invalid with respect to Zebra + */ + public static Zebra fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, Zebra.class); + } + + /** + * Convert an instance of Zebra to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 000000000000..156caa9794f5 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,380 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; + +import okhttp3.OkHttpClient; +import org.junit.jupiter.api.*; +import org.openapitools.client.auth.*; + +public class ApiClientTest { + ApiClient apiClient; + JSON json; + + @BeforeEach + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + + assertTrue(apiClient.isJsonMime("application/json-patch+json")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals( + "application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertNull(apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + /* + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + */ + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testGetAndSetConnectTimeout() { + // connect timeout defaults to 10 seconds + assertEquals(10000, apiClient.getConnectTimeout()); + assertEquals(10000, apiClient.getHttpClient().connectTimeoutMillis()); + + apiClient.setConnectTimeout(0); + assertEquals(0, apiClient.getConnectTimeout()); + assertEquals(0, apiClient.getHttpClient().connectTimeoutMillis()); + + apiClient.setConnectTimeout(10000); + } + + @Test + public void testGetAndSetReadTimeout() { + // read timeout defaults to 10 seconds + assertEquals(10000, apiClient.getReadTimeout()); + assertEquals(10000, apiClient.getHttpClient().readTimeoutMillis()); + + apiClient.setReadTimeout(0); + assertEquals(0, apiClient.getReadTimeout()); + assertEquals(0, apiClient.getHttpClient().readTimeoutMillis()); + + apiClient.setReadTimeout(10000); + } + + @Test + public void testGetAndSetWriteTimeout() { + // write timeout defaults to 10 seconds + assertEquals(10000, apiClient.getWriteTimeout()); + assertEquals(10000, apiClient.getHttpClient().writeTimeoutMillis()); + + apiClient.setWriteTimeout(0); + assertEquals(0, apiClient.getWriteTimeout()); + assertEquals(0, apiClient.getHttpClient().writeTimeoutMillis()); + + apiClient.setWriteTimeout(10000); + } + + @Test + public void testParameterToPairWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPair(null, new Integer(1)); + List pairs_b = apiClient.parameterToPair("", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPair("param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsEmptyString() throws Exception { + // single empty string + List pairs = apiClient.parameterToPair("param-a", " "); + assertEquals(1, pairs.size()); + } + + @Test + public void testParameterToPairWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPair(name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairWhenValueIsCollection() throws Exception { + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + List pairs = apiClient.parameterToPair("param-a", values); + assertEquals(0, pairs.size()); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List objects = new ArrayList(); + objects.add(new Integer(1)); + + List pairs_a = apiClient.parameterToPairs("csv", null, objects); + List pairs_b = apiClient.parameterToPairs("csv", "", objects); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + for (int i = 0; i < values.size(); i++) { + assertEquals( + apiClient.escapeString(apiClient.parameterToString(values.get(i))), + multiPairs.get(i).getValue()); + } + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + if (!delimiter.equals(",")) { + // commas are not escaped because they are reserved characters in URIs + delimiter = apiClient.escapeString(delimiter); + } + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + for (int i = 0; i < values.size(); i++) { + assertEquals( + apiClient.escapeString(apiClient.parameterToString(values.get(i))), + pairValueSplit[i]); + } + } + } + + @Test + public void testSanitizeFilename() { + assertEquals("sun", apiClient.sanitizeFilename("sun")); + assertEquals("sun.gif", apiClient.sanitizeFilename("sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("../sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("/var/tmp/sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("./sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("..\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("c:\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename(".\\sun.gif")); + } + + @Test + public void testNewHttpClient() { + OkHttpClient oldClient = apiClient.getHttpClient(); + apiClient.setHttpClient(oldClient.newBuilder().build()); + assertNotSame(apiClient.getHttpClient(), oldClient); + } + + /** + * Tests the invariant that the HttpClient for the ApiClient must never be null + */ + @Test + public void testNullHttpClient() { + NullPointerException thrown = Assertions.assertThrows(NullPointerException.class, () -> { + apiClient.setHttpClient(null); + }); + Assertions.assertEquals("HttpClient must not be null!", thrown.getMessage()); + } + @Test + public void testParameterToJsonStringNull() { + assertEquals("", apiClient.parameterToString(null)); + assertEquals("", apiClient.parameterToJsonString(null)); + } + + @Test + public void testParameterToJsonStringAscii() { + Map value = new HashMap<>(); + value.put("path", "/x"); + + assertEquals("{\"path\":\"/x\"}", apiClient.parameterToJsonString(value)); + } + + @Test + public void testParameterToJsonStringEscapesNonAscii() { + Map value = new HashMap<>(); + value.put("path", "/тест"); + + assertEquals("{\"path\":\"/\\u0442\\u0435\\u0441\\u0442\"}", apiClient.parameterToJsonString(value)); + } + + @Test + public void testParameterToJsonStringEscapesDel() { + Map value = new HashMap<>(); + value.put("path", "/\u007f"); + + assertEquals("{\"path\":\"/\\u007f\"}", apiClient.parameterToJsonString(value)); + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ClientTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ClientTest.java new file mode 100644 index 000000000000..10fa9f118fe4 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ClientTest.java @@ -0,0 +1,83 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; + +import okhttp3.OkHttpClient; +import org.junit.jupiter.api.*; +import org.openapitools.client.auth.*; + +import java.math.BigDecimal; + +import org.openapitools.client.model.*; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +public class ClientTest { + ApiClient apiClient; + JSON json; + + @BeforeEach + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + } + + /** + * Test the property 'arrayArrayNumber' + */ + @Test + public void arrayArrayNumberTest() { + ArrayOfArrayOfNumberOnly model = new ArrayOfArrayOfNumberOnly(); + BigDecimal b1 = new BigDecimal("12.3"); + BigDecimal b2 = new BigDecimal("5.6"); + List arrayArrayNumber = new ArrayList(); + arrayArrayNumber.add(b1); + arrayArrayNumber.add(b2); + model.setArrayArrayNumber(new ArrayList>()); + model.getArrayArrayNumber().add(arrayArrayNumber); + + // create another instance for comparison + BigDecimal b3 = new BigDecimal("12.3"); + BigDecimal b4 = new BigDecimal("5.6"); + ArrayOfArrayOfNumberOnly model2 = new ArrayOfArrayOfNumberOnly(); + List arrayArrayNumber2 = new ArrayList(); + arrayArrayNumber2.add(b1); + arrayArrayNumber2.add(b2); + model2.setArrayArrayNumber(new ArrayList>()); + model2.getArrayArrayNumber().add(arrayArrayNumber2); + + // NOTE: the okhttp library's generated equals() delegates to + // EqualsBuilder.reflectionEquals(this, o, false, null, true) (commons-lang3), which + // (with testRecursive=true) walks into java.util.ArrayList's own fields reflectively + // for any List-typed property -- including the empty ArrayList that + // ArrayOfArrayOfNumberOnly's `arrayArrayNumber` field defaults to. On JDK 9+, that + // throws InaccessibleObjectException unless the JVM is launched with + // `--add-opens java.base/java.util=ALL-UNNAMED`, which this sample's generated pom.xml + // does not set. Assert on the field value directly instead of via equals(). + Assertions.assertEquals(model2.getArrayArrayNumber(), model.getArrayArrayNumber()); + } + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + Pet model = new Pet(); + // test Pet + model.setId(1029L); + model.setName("Dog"); + + Pet model2 = new Pet(); + model2.setId(1029L); + model2.setName("Dog"); + + // NOTE: see the comment in arrayArrayNumberTest() above -- Pet's generated equals() + // reflectively walks into its default-initialized `photoUrls`/`tags` List fields via + // commons-lang3's EqualsBuilder.reflectionEquals(..., true), which fails on JDK 9+ + // without extra JVM `--add-opens` flags. Assert on the field values directly instead. + Assertions.assertEquals(model.getId(), model2.getId()); + Assertions.assertEquals(model.getName(), model2.getName()); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ConfigurationTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ConfigurationTest.java new file mode 100644 index 000000000000..e5b9d146a4eb --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.*; + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/JSONTest.java new file mode 100644 index 000000000000..9588c28aae1d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/JSONTest.java @@ -0,0 +1,838 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.*; + +import okio.ByteString; +import org.junit.jupiter.api.*; +import org.openapitools.client.model.Order; + +import org.openapitools.client.model.*; + +public class JSONTest { + private ApiClient apiClient = null; + private JSON json = null; + private Order order = null; + + @BeforeEach + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + order = new Order(); + } + + @Test + public void testAnyOfWithNullableRequiredFields() { + Gson gson = json.getGson(); + + // Test: anyOf response with nullable required fields set to null should deserialize + // This reproduces the bug where Record + // fails anyOf matching when field values are null. + String jsonStr = "{\"status\":\"success\",\"positions\":{\"comment1\":{\"before\":null,\"after\":\"3\"},\"comment2\":{\"before\":\"1\",\"after\":null}}}"; + NullableFieldsMapResponse response = gson.fromJson(jsonStr, NullableFieldsMapResponse.class); + assertNotNull(response); + NullableFieldsMapSuccess success = response.getNullableFieldsMapSuccess(); + assertNotNull(success); + assertEquals("success", success.getStatus()); + assertNotNull(success.getPositions()); + assertNull(success.getPositions().get("comment1").getBefore()); + assertEquals("3", success.getPositions().get("comment1").getAfter()); + assertEquals("1", success.getPositions().get("comment2").getBefore()); + assertNull(success.getPositions().get("comment2").getAfter()); + } + + @Test + public void testAnyOfWithNullableRequiredFieldsBothNull() { + Gson gson = json.getGson(); + + // Both nullable fields are null + String jsonStr = "{\"status\":\"success\",\"positions\":{\"comment1\":{\"before\":null,\"after\":null}}}"; + NullableFieldsMapResponse response = gson.fromJson(jsonStr, NullableFieldsMapResponse.class); + assertNotNull(response); + NullableFieldsMapSuccess success = response.getNullableFieldsMapSuccess(); + assertNotNull(success); + assertNull(success.getPositions().get("comment1").getBefore()); + assertNull(success.getPositions().get("comment1").getAfter()); + } + + @Test + public void testOneOfFreeFormObject() { + final Map map = new LinkedHashMap<>(); + map.put("someString", "abc"); + map.put("someBoolean", false); + + final String json1 = "{\"someString\":\"abc\",\"someBoolean\":false}"; + final FreeFormObjectTestClassProperties properties = new FreeFormObjectTestClassProperties(); + properties.setActualInstance(map); + + assertEquals(json1, json.serialize(properties)); + assertEquals(json.deserialize(json1, FreeFormObjectTestClassProperties.class), properties); + + final String json2 = "\"abc\""; + final FreeFormObjectTestClassProperties properties2 = new FreeFormObjectTestClassProperties(); + properties2.setActualInstance("abc"); + + assertEquals(json2, json.serialize(properties2)); + assertEquals(json.deserialize(json2, FreeFormObjectTestClassProperties.class), properties2); + } + + @Test + public void testSqlDateTypeAdapter() { + final String str = "\"2015-11-07\""; + final java.sql.Date date = java.sql.Date.valueOf("2015-11-07"); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, java.sql.Date.class), date); + assertEquals( + json.deserialize( + "\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", + java.sql.Date.class) + .toString(), + date.toString()); + + // custom date format: without day + DateFormat format = new SimpleDateFormat("yyyy-MM", Locale.ROOT); + apiClient.setSqlDateFormat(format); + String dateStr = "\"2015-11\""; + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class))); + } + + @Test + public void testDateTypeAdapter() { + Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + + assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 300); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 356); + Date date = cal.getTime(); + + final String utcDate = "\"2015-11-07T03:49:09.356Z\""; + assertEquals(json.deserialize(utcDate, Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date); + + assertEquals(utcDate, json.serialize(date)); + + // custom datetime format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ROOT); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + + String dateStr = "\"2015-11-07T13:49:09+10:00\""; + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class))); + assertEquals( + dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class))); + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class))); + + try { + // invalid time zone format + json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + try { + // unexpected milliseconds + json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void testOffsetDateTimeTypeAdapter() { + final String str = "\"2016-09-09T08:02:03.123-03:00\""; + OffsetDateTime date = + OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3")); + + assertEquals(str, json.serialize(date)); + // Use toString() instead of isEqual to verify that the offset is preserved + assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString()); + } + + @Test + public void testLocalDateTypeAdapter() { + final String str = "\"2016-09-09\""; + final LocalDate date = LocalDate.of(2016, 9, 9); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, LocalDate.class), date); + } + + @Test + public void testLocalDateTimeTypeAdapter() { + final String str = "\"2016-09-09T08:02:03\""; + final LocalDateTime date = LocalDateTime.of(2016, 9, 9, 8, 2, 3); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, LocalDateTime.class), date); + assertNull(json.deserialize("null", LocalDateTime.class)); + } + + @Test + public void testLocalDateTimeTypeAdapterWithSpaceSeparator() { + // RFC 3339 section 5.6 permits a space in place of the ISO 8601 'T' separator + final LocalDateTime date = LocalDateTime.of(2016, 9, 9, 8, 2, 3); + + assertEquals(json.deserialize("\"2016-09-09 08:02:03\"", LocalDateTime.class), date); + assertEquals("\"2016-09-09T08:02:03\"", json.serialize(date)); + } + + @Test + public void testLocalDateTimeTypeAdapterWithCustomFormat() { + final String str = "\"2016-09-09 08:02:03\""; + final LocalDateTime date = LocalDateTime.of(2016, 9, 9, 8, 2, 3); + + JSON.setLocalDateTimeFormat(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")); + try { + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, LocalDateTime.class), date); + } finally { + JSON.setLocalDateTimeFormat(DateTimeFormatter.ISO_LOCAL_DATE_TIME); + } + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); + + String str = json.serialize(order); + Type type = new TypeToken() { + }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter datetimeFormat = + DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); + + String str = json.serialize(order); + Type type = new TypeToken() { + }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testByteArrayTypeAdapterSerialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + + // Act + String serializedBytesWithQuotes = json.serialize(expectedBytes); + + // Assert + String serializedBytes = + serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1); + if (json.getGson().htmlSafe()) { + serializedBytes = serializedBytes.replaceAll("\\\\u003d", "="); + } + ByteString actualAsByteString = ByteString.decodeBase64(serializedBytes); + byte[] actualBytes = actualAsByteString.toByteArray(); + assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testByteArrayTypeAdapterDeserialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + final ByteString expectedByteString = ByteString.of(expectedBytes); + final String serializedBytes = expectedByteString.base64(); + final String serializedBytesWithQuotes = "\"" + serializedBytes + "\""; + Type type = new TypeToken() { + }.getType(); + + // Act + byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type); + + // Assert + assertEquals( + expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testRequiredFieldException() { + IllegalArgumentException thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> { + // test json string missing required field(s) to ensure exception is thrown + Gson gson = json.getGson(); + String json = "{\"id\": 5847, \"name\":\"tag test 1\"}"; // missing photoUrls (required field) + Pet p = gson.fromJson(json, Pet.class); + }); + + Assertions.assertEquals("The required field `photoUrls` is not found in the JSON string: {\"id\":5847,\"name\":\"tag test 1\"}", thrown.getMessage()); + } + + @Test + @Disabled("No longer need the following test as additional field(s) should be stored in `additionalProperties`") + public void testAdditionalFieldException() { + IllegalArgumentException thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> { + // test json string with additional field(s) to ensure exception is thrown + Gson gson = json.getGson(); + String json = "{\"id\": 5847, \"name\":\"tag test 1\", \"new-field\": true}"; + org.openapitools.client.model.Tag t = gson.fromJson(json, org.openapitools.client.model.Tag.class); + }); + + Assertions.assertEquals("The field `new-field` in the JSON string is not defined in the `Tag` properties. JSON: {\"id\":5847,\"name\":\"tag test 1\",\"new-field\":true}", thrown.getMessage()); + } + + @Test + public void testCustomDeserializer() { + // test the custom deserializer to ensure it can deserialize json payload into objects + Gson gson = json.getGson(); + // id and name + String json = "{\"id\": 5847, \"name\":\"tag test 1\"}"; + org.openapitools.client.model.Tag t = gson.fromJson(json, org.openapitools.client.model.Tag.class); + assertEquals(t.getName(), "tag test 1"); + assertEquals(t.getId(), Long.valueOf(5847L)); + + // name only + String json2 = "{\"name\":\"tag test 1\"}"; + org.openapitools.client.model.Tag t2 = gson.fromJson(json2, org.openapitools.client.model.Tag.class); + assertEquals(t2.getName(), "tag test 1"); + assertEquals(t2.getId(), null); + + // with all required fields + String json3 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"]}"; + Pet t3 = gson.fromJson(json3, Pet.class); + assertEquals(t3.getName(), "pet test 1"); + assertEquals(t3.getId(), Long.valueOf(5847)); + + // with all required fields and tags (optional) + String json4 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"id\":\"tag 123\"}]}"; + Pet t4 = gson.fromJson(json3, Pet.class); + assertEquals(t4.getName(), "pet test 1"); + assertEquals(t4.getId(), Long.valueOf(5847)); + } + + @Test + @Disabled("Unknown fields are now correctly deserialized into `additionalProperties`") + public void testUnknownFields() { + // test unknown fields in the payload + Gson gson = json.getGson(); + // test Tag + String json5 = "{\"unknown_field\": 543, \"id\":\"tag 123\"}"; + Exception exception5 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + org.openapitools.client.model.Tag t5 = gson.fromJson(json5, org.openapitools.client.model.Tag.class); + }); + assertTrue(exception5.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}")); + + // test Pet with invalid tags + String json6 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"unknown_field\": 543, \"id\":\"tag 123\"}]}"; + Exception exception6 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet t6 = gson.fromJson(json6, Pet.class); + }); + assertTrue(exception6.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}")); + + // test Pet with invalid tags (required) + String json7 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"unknown_field\": 543, \"id\":\"tag 123\"}]}"; + Exception exception7 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + PetWithRequiredTags t7 = gson.fromJson(json7, PetWithRequiredTags.class); + }); + assertTrue(exception7.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}")); + + // test Pet with invalid tags (missing reqired) + String json8 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"]}"; + Exception exception8 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + PetWithRequiredTags t8 = gson.fromJson(json8, PetWithRequiredTags.class); + }); + assertTrue(exception8.getMessage().contains("The required field `tags` is not found in the JSON string: {\"id\":5847,\"name\":\"pet test 1\",\"photoUrls\":[\"https://a.com\",\"https://b.com\"]}")); + } + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // test Pet + Pet model = new Pet(); + model.setId(1029L); + model.setName("Dog"); + + Pet model2 = new Pet(); + model2.setId(1029L); + model2.setName("Dog"); + + // NOTE: the okhttp library's generated Pet.equals() delegates to commons-lang3's + // EqualsBuilder.reflectionEquals(this, o, false, null, true), which (with + // testRecursive=true) reflectively walks into java.util.ArrayList's own fields for + // Pet's default-initialized `photoUrls`/`tags` List properties. On JDK 9+ this throws + // InaccessibleObjectException unless the test JVM is launched with + // `--add-opens java.base/java.util=ALL-UNNAMED`, which this sample's generated pom.xml + // does not set. Assert on the field values directly instead of via equals(). + assertEquals(model.getId(), model2.getId()); + assertEquals(model.getName(), model2.getName()); + } + + // Obtained 22JAN2018 from stackoverflow answer by PuguaSoft + // https://stackoverflow.com/questions/11399491/java-timezone-offset + // Direct link https://stackoverflow.com/a/16680815/3166133 + public static String getCurrentTimezoneOffset() { + + TimeZone tz = TimeZone.getDefault(); + Calendar cal = GregorianCalendar.getInstance(tz, Locale.ROOT); + int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); + + String offset = + String.format( + Locale.ROOT, + "%02d:%02d", + Math.abs(offsetInMillis / 3600000), + Math.abs((offsetInMillis / 60000) % 60)); + offset = (offsetInMillis >= 0 ? "+" : "-") + offset; + + return offset; + } + + /** + * Validate an anyOf schema can be deserialized into the expected class. + * The anyOf schema does not have a discriminator. + */ + @Test + public void testAnyOfSchemaWithoutDiscriminator() throws Exception { + { + String str = "{ \"cultivar\": \"golden delicious\", \"origin\": \"japan\" }"; + + // make sure deserialization works for pojo object + Apple a = json.getGson().fromJson(str, Apple.class); + assertEquals(a.getCultivar(), "golden delicious"); + assertEquals(a.getOrigin(), "japan"); + + GmFruit o = json.getGson().fromJson(str, GmFruit.class); + assertTrue(o.getActualInstance() instanceof Apple); + Apple inst = (Apple) o.getActualInstance(); + assertEquals(inst.getCultivar(), "golden delicious"); + assertEquals(inst.getOrigin(), "japan"); + assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}"); + assertEquals(inst.toJson(), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}"); + assertEquals(o.toJson(), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}"); + } + } + + /** + * Validate a oneOf schema can be deserialized into the expected class. + * The oneOf schema has a discriminator. + * + * NOTE: unlike the okhttp-gson library, the okhttp library's discriminated oneOf + * wrapper (Mammal) does not expose fromJson/toJson convenience methods, and its + * generated deserializer treats a missing discriminator field as an immediate, + * hard failure rather than falling back to trying each oneOf schema in turn. + */ + @Test + public void testOneOfSchemaWithDiscriminator() throws Exception { + { + String str = "{ \"className\": \"whale\", \"hasBaleen\": false, \"hasTeeth\": false }"; + + // make sure deserialization works for pojo object + Whale w = json.getGson().fromJson(str, Whale.class); + assertEquals(w.getClassName(), "whale"); + assertEquals(w.getHasBaleen(), false); + assertEquals(w.getHasTeeth(), false); + + Mammal o = Mammal.fromJson(str); + assertTrue(o.getActualInstance() instanceof Whale); + Whale inst = (Whale) o.getActualInstance(); + assertEquals(inst.getClassName(), "whale"); + assertEquals(inst.getHasBaleen(), false); + assertEquals(inst.getHasTeeth(), false); + assertEquals(json.getGson().toJson(inst), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + assertEquals(inst.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + assertEquals(o.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + + String str2 = "{ \"className\": \"zebra\", \"type\": \"plains\" }"; + + // make sure deserialization works for pojo object + Zebra z = Zebra.fromJson(str2); + assertEquals(z.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + + Mammal o2 = Mammal.fromJson(str2); + assertTrue(o2.getActualInstance() instanceof Zebra); + Zebra inst2 = (Zebra) o2.getActualInstance(); + assertEquals(json.getGson().toJson(inst2), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + assertEquals(inst2.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + assertEquals(o2.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + } + { + // incorrect payload (no `className` discriminator at all) results in exception. + // The okhttp library's Mammal deserializer fails fast on a missing discriminator + // instead of falling back to trying each oneOf schema. + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false, \"garbage_prop\": \"abc\" }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + Mammal o = Mammal.fromJson(str); + }); + assertTrue(exception.getMessage().contains("Failed to deserialize as the discriminator field 'className' is missing.")); + } + { + // Try to deserialize empty object. This should fail because the discriminator + // field `className` is missing. + String str = "{ }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + json.getGson().fromJson(str, Mammal.class); + }); + assertTrue(exception.getMessage().contains("Failed to deserialize as the discriminator field 'className' is missing.")); + } + } + + /** + * Validate an anyOf schema can be deserialized into the expected class. + * The anyOf schema has a discriminator. + */ + @Test + public void testAnyOfSchemaWithDiscriminator() throws Exception { + { + // Zebra is listed after Whale in anyOf, and a zebra payload also satisfies Whale + // (className is Whale's only required field), so without the discriminator lookup + // this deserializes as Whale. + String str = "{ \"className\": \"zebra\", \"type\": \"plains\" }"; + + MammalAnyof o = json.getGson().fromJson(str, MammalAnyof.class); + assertTrue(o.getActualInstance() instanceof Zebra); + Zebra inst = (Zebra) o.getActualInstance(); + assertEquals(inst.getClassName(), "zebra"); + assertEquals(inst.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + assertEquals(o.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + } + { + String str = "{ \"className\": \"whale\", \"hasBaleen\": false, \"hasTeeth\": false }"; + + MammalAnyof o = json.getGson().fromJson(str, MammalAnyof.class); + assertTrue(o.getActualInstance() instanceof Whale); + Whale inst = (Whale) o.getActualInstance(); + assertEquals(inst.getClassName(), "whale"); + assertEquals(inst.getHasBaleen(), false); + assertEquals(inst.getHasTeeth(), false); + assertEquals(inst.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + assertEquals(o.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + } + { + // an unmapped discriminator value falls back to matching the anyOf schemas in order + String str = "{ \"className\": \"dolphin\", \"hasBaleen\": true }"; + + MammalAnyof o = json.getGson().fromJson(str, MammalAnyof.class); + assertTrue(o.getActualInstance() instanceof Whale); + Whale inst = (Whale) o.getActualInstance(); + assertEquals(inst.getClassName(), "dolphin"); + assertEquals(inst.getHasBaleen(), true); + } + { + // Try to deserialize empty object. This should fail 'anyOf' because none will match + // whale, zebra or Pig. + String str = "{ }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + json.getGson().fromJson(str, MammalAnyof.class); + }); + assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for MammalAnyof")); + } + } + + /** + * Test JSON validation method + */ + @Test + public void testJsonValidation() throws Exception { + String str = "{ \"cultivar\": [\"golden delicious\"], \"mealy\": false }"; + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + AppleReq a = json.getGson().fromJson(str, AppleReq.class); + }); + assertTrue(exception.getMessage().contains("Expected the field `cultivar` to be a primitive type in the JSON string but got `[\"golden delicious\"]`")); + + String str2 = "{ \"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": 123 }"; + Exception exception2 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet p1 = json.getGson().fromJson(str2, Pet.class); + }); + assertTrue(exception2.getMessage().contains("Expected the field `photoUrls` to be an array in the JSON string but got `123`")); + } + + /** + * Validate a oneOf schema can be deserialized into the expected class. + * The oneOf schema does not have a discriminator. + * + * NOTE: unlike the okhttp-gson library, the okhttp library's FruitReq oneOf wrapper + * does not expose fromJson/toJson convenience methods (only the leaf schemas + * AppleReq/BananaReq do), and the failure message format for an ambiguous/unmatched + * oneOf no longer includes the "Detailed failure message for oneOf schemas:" / trailing + * "JSON: ..." text; it is now "Failed deserialization for FruitReq: N classes match + * result, expected 1. [errors]". + */ + @Test + public void testOneOfSchemaWithoutDiscriminator() throws Exception { + // BananaReq and AppleReq have explicitly defined properties that are different by name. + // There is no discriminator property. + { + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false }"; + + // make sure deserialization works for pojo object + AppleReq a = json.getGson().fromJson(str, AppleReq.class); + assertEquals(a.getCultivar(), "golden delicious"); + assertEquals(a.getMealy(), false); + + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + assertTrue(o.getActualInstance() instanceof AppleReq); + AppleReq inst = (AppleReq) o.getActualInstance(); + assertEquals(inst.getCultivar(), "golden delicious"); + assertEquals(inst.getMealy(), false); + assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(inst.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(o.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + + AppleReq inst2 = o.getAppleReq(); + assertEquals(inst2.getCultivar(), "golden delicious"); + assertEquals(inst2.getMealy(), false); + assertEquals(json.getGson().toJson(inst2), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(inst2.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + + // test fromJson (FruitReq has no fromJson of its own; use the shared Gson instead) + FruitReq o3 = json.getGson().fromJson(str, FruitReq.class); + assertTrue(o3.getActualInstance() instanceof AppleReq); + AppleReq inst3 = (AppleReq) o3.getActualInstance(); + assertEquals(inst3.getCultivar(), "golden delicious"); + assertEquals(inst3.getMealy(), false); + assertEquals(json.getGson().toJson(inst3), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(inst3.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + } + { + // test to ensure the oneOf object can be serialized to "null" correctly + FruitReq o = new FruitReq(); + assertEquals(o.getActualInstance(), null); + assertEquals(o.toJson(), "null"); + assertEquals(json.getGson().toJson(null), "null"); + } + { + // Same test, but this time with additional (undeclared) properties. + // Since FruitReq has additionalProperties: false, deserialization should fail. + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false, \"garbage_prop\": \"abc\" }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + }); + assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for FruitReq: 0 classes match result, expected 1.")); + assertTrue(exception.getMessage().contains("Deserialization for AppleReq failed with")); + assertTrue(exception.getMessage().contains("Deserialization for BananaReq failed with")); + assertTrue(exception.getMessage().contains("garbage_prop")); + } + { + String str = "{ \"lengthCm\": 17 }"; + + // make sure deserialization works for pojo object + BananaReq b = json.getGson().fromJson(str, BananaReq.class); + assertEquals(b.getLengthCm(), new java.math.BigDecimal(17)); + + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + assertTrue(o.getActualInstance() instanceof BananaReq); + BananaReq inst = (BananaReq) o.getActualInstance(); + assertEquals(inst.getLengthCm(), new java.math.BigDecimal(17)); + assertEquals(o.toJson(), "{\"lengthCm\":17}"); + assertEquals(json.getGson().toJson(inst), "{\"lengthCm\":17}"); + } + { + // Try to deserialize empty object. This should fail 'oneOf' because none will match + // AppleReq or BananaReq. + String str = "{ }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + json.getGson().fromJson(str, FruitReq.class); + }); + assertTrue(exception.getMessage().contains("Failed deserialization for FruitReq: 0 classes match result, expected 1")); + } + } + + + /** + * Test validateJsonObject with null object + */ + @Test + public void testValidateJsonObject() throws Exception { + JsonObject jsonObject = new JsonObject(); + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet.validateJsonElement(jsonObject); + }); + assertEquals(exception.getMessage(), "The required field `photoUrls` is not found in the JSON string: {}"); + } + + /** + * Test additional properties. + */ + @Test + public void testAdditionalProperties() throws Exception { + String str = "{ \"className\": \"zebra\", \"type\": \"plains\", \"from_json\": 4567, \"from_json_map\": {\"nested_string\": \"nested_value\"} }"; + Zebra z = Zebra.fromJson(str); + z.putAdditionalProperty("new_key", "new_value"); + z.putAdditionalProperty("new_number", 1.23); + z.putAdditionalProperty("new_boolean", true); + org.openapitools.client.model.Tag t = new org.openapitools.client.model.Tag(); + t.setId(34L); + t.setName("just a tag"); + z.putAdditionalProperty("new_object", t); + assertEquals(z.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\",\"new_key\":\"new_value\",\"new_boolean\":true,\"new_object\":{\"id\":34,\"name\":\"just a tag\"},\"from_json\":4567,\"from_json_map\":{\"nested_string\":\"nested_value\"},\"new_number\":1.23}"); + } + + + @Test + public void testInvalidEnumValueException() { + // test Pet with invalid status + String str = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"status\":\"sleeping\"}"; + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet t7 = Pet.fromJson(str); + }); + assertTrue(exception.getMessage().contains("Unexpected value 'sleeping'")); + } + + @Test + public void testPetUsingAllOf() { + Gson gson = json.getGson(); + String json = "{\"photoUrls\":[\"http://a.com\"], \"id\": 5847, \"name\":\"tag test 1\", \"category\": {\"id\":888, \"name\":\"cat 1\"}, \"tags\":[ {\"id\":777, \"name\":\"tag 1\"}] }"; + PetUsingAllOf p = gson.fromJson(json, PetUsingAllOf.class); + assertEquals(p.getId(), 5847L); + assertEquals(p.getName(), "tag test 1"); + assertEquals(p.getCategory().getId(), 888L); + assertEquals(p.getCategory().getName(), "cat 1"); + assertEquals(p.getTags().get(0).getId(), 777L); + assertEquals(p.getTags().get(0).getName(), "tag 1"); + } + + @Test + public void testAdditionalArrayProperties() throws IOException { + String str = "{ \"className\": \"zebra\", \"array\": [\"1\",\"2\",\"3\"], \"empty_array\": [], \"object_array\": [{\"id\": 34, \"name\": \"just a tag\"}] }"; + Zebra z = Zebra.fromJson(str); + z.putAdditionalProperty("new_array", Arrays.asList("1", "2", "3")); + z.putAdditionalProperty("new_empty_array", new ArrayList<>()); + org.openapitools.client.model.Tag t = new org.openapitools.client.model.Tag(); + t.setId(34L); + t.setName("just a tag"); + z.putAdditionalProperty("new_object_array", Arrays.asList(t)); + assertEquals(z.toJson(), "{\"className\":\"zebra\",\"object_array\":[{\"id\":34.0,\"name\":\"just a tag\"}],\"empty_array\":[],\"array\":[\"1\",\"2\",\"3\"],\"new_array\":[\"1\",\"2\",\"3\"],\"new_empty_array\":[],\"new_object_array\":[{\"id\":34,\"name\":\"just a tag\"}]}"); + } + + /** + * Validate a oneOf, anyOf schema with array sub-schema can be deserialized into the expected class. + * + * NOTE: the okhttp library's composed-array wrapper failure message format no longer + * includes "The JSON string is invalid for ..."; it is now + * "Failed deserialization for ArrayOneOf/ArrayAnyOf: ...". + */ + @Test + public void testOneOfAnyOfArray() throws Exception { + { + String str = "{\"oneof_prop\":23,\"anyof_prop\":45}"; + + ModelWithOneOfAnyOfProperties m = json.getGson().fromJson(str, ModelWithOneOfAnyOfProperties.class); + Integer anyofProp = (Integer) m.getAnyofProp().getActualInstance(); + assertEquals(anyofProp, 45); + Integer oneofProp = (Integer) m.getOneofProp().getActualInstance(); + assertEquals(oneofProp, 23); + + String str2 = "{ \"oneof_prop\": [\"test oneof\"], \"anyof_prop\": [\"test anyof\"] }"; + + ModelWithOneOfAnyOfProperties m2 = json.getGson().fromJson(str2, ModelWithOneOfAnyOfProperties.class); + List anyofProp2 = (List) m2.getAnyofProp().getActualInstance(); + assertEquals(anyofProp2, Arrays.asList("test anyof")); + List oneofProp2 = (List) m2.getOneofProp().getActualInstance(); + assertEquals(oneofProp2, Arrays.asList("test oneof")); + } + { + // incorrect payload results in exception + String str = "{ \"oneof_prop\": \"23\", \"anyof_prop\": \"45\" }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + ModelWithOneOfAnyOfProperties o = json.getGson().fromJson(str, ModelWithOneOfAnyOfProperties.class); + }); + assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for ArrayOneOf")); + } + { + // incorrect payload (array item type mismatch) results in exception + String str = "{ \"oneof_prop\": [23], \"anyof_prop\": [true] }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + ModelWithOneOfAnyOfProperties o = json.getGson().fromJson(str, ModelWithOneOfAnyOfProperties.class); + }); + assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for ArrayOneOf")); + } + } + + @Test + public void testRequiredNullableBody() throws Exception { + final String json1 = "{\"integer_prop\":null,\"number_prop\":null,\"boolean_prop\":null,\"string_prop\":null,\"date_prop\":null,\"datetime_prop\":null,\"array_nullable_prop\":null,\"array_and_items_nullable_prop\":null,\"array_items_nullable\":[],\"object_nullable_prop\":null,\"object_and_items_nullable_prop\":null,\"object_items_nullable\":{},\"custom_ref_enum\":null,\"custom_enum\":null}"; + final RequiredNullableBody body = new RequiredNullableBody(); + + assertEquals("{\"array_items_nullable\":[],\"object_items_nullable\":{}}", json.serialize(body)); + // NOTE: RequiredNullableBody.equals() (like Pet's, see testPet() above) delegates to + // commons-lang3's EqualsBuilder.reflectionEquals(..., true), which reflectively walks + // into the default-initialized `arrayItemsNullable`/`objectItemsNullable` List/Map + // fields and throws InaccessibleObjectException on JDK 9+ without extra `--add-opens` + // JVM flags this sample's generated pom.xml does not set. Compare the serialized form + // instead of calling equals() directly. + final RequiredNullableBody deserialized = json.deserialize(json1, RequiredNullableBody.class); + assertEquals(json.serialize(body), json.serialize(deserialized)); + } + + @Test + public void testDeserializeInputStream() throws Exception { + final String str = "\"2016-09-09\""; + final InputStream inputStream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8)); + final LocalDate date = LocalDate.of(2016, 9, 9); + assertEquals(date, json.deserialize(inputStream, LocalDate.class)); + } + + @Test + public void testOneOfAnyOfPropertyNull() throws Exception { + // oneOf/anyOf TypeAdapters must be null-safe: a JSON null for a composed-schema-typed + // property has to deserialize to null instead of failing on "Not a JSON Object: null" + String str = "{\"shapeOrNull\":null,\"nullableShape\":null}"; + + Drawing drawing = json.getGson().fromJson(str, Drawing.class); + assertNull(drawing.getShapeOrNull()); + assertNull(drawing.getNullableShape()); + + // and the adapters must write null back out instead of throwing + assertNull(json.getGson().fromJson("null", ShapeOrNull.class)); + assertEquals("null", json.getGson().toJson(null, ShapeOrNull.class)); + } + + @Test + public void testValidateJsonElementNull() throws Exception { + // no required fields: a null element is an empty JSON object, there is nothing left to validate + org.openapitools.client.model.Tag.validateJsonElement(null); + // required fields: must be reported as missing instead of failing with a NullPointerException + IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> Category.validateJsonElement(null)); + assertTrue(e.getMessage().contains("name"), e.getMessage()); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ProgressRequestBodyTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ProgressRequestBodyTest.java new file mode 100644 index 000000000000..1d259e57135c --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ProgressRequestBodyTest.java @@ -0,0 +1,99 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import okhttp3.MediaType; +import okhttp3.RequestBody; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; +import okio.Sink; +import org.junit.jupiter.api.Test; + +public class ProgressRequestBodyTest { + + private static class RecordingCallback implements ApiCallback { + final List doneFlags = new ArrayList<>(); + long lastBytesWritten = -1; + + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + } + + @Override + public void onSuccess(Object result, int statusCode, Map> responseHeaders) { + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + doneFlags.add(done); + lastBytesWritten = bytesWritten; + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + } + } + + @Test + public void nonDuplexBodyReportsCompletionWhenWriteToReturns() throws IOException { + RecordingCallback callback = new RecordingCallback(); + ProgressRequestBody body = new ProgressRequestBody( + RequestBody.create("hello", MediaType.get("text/plain")), callback); + + Buffer out = new Buffer(); + BufferedSink sink = Okio.buffer((Sink) out); + body.writeTo(sink); + sink.flush(); + + assertEquals("hello", out.readUtf8()); + assertFalse(callback.doneFlags.isEmpty()); + assertTrue(callback.doneFlags.get(callback.doneFlags.size() - 1), "last event must be the terminal one"); + assertEquals(5, callback.lastBytesWritten); + } + + @Test + public void duplexBodyReportsCompletionOnlyWhenTheDelegateClosesTheSink() throws IOException { + RecordingCallback callback = new RecordingCallback(); + BufferedSink[] captured = new BufferedSink[1]; + RequestBody duplex = new RequestBody() { + @Override + public MediaType contentType() { + return MediaType.get("application/octet-stream"); + } + + @Override + public boolean isDuplex() { + return true; + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + // a duplex body hands the sink to another writer and returns before the upload is over + sink.writeUtf8("part1"); + sink.flush(); + captured[0] = sink; + } + }; + ProgressRequestBody body = new ProgressRequestBody(duplex, callback); + assertTrue(body.isDuplex()); + + Buffer out = new Buffer(); + body.writeTo(Okio.buffer((Sink) out)); + assertFalse(callback.doneFlags.contains(true), "completion must not be reported while the delegate may still write"); + + captured[0].writeUtf8("part2"); + captured[0].flush(); + assertFalse(callback.doneFlags.contains(true)); + + captured[0].close(); + assertEquals("part1part2", out.readUtf8()); + assertTrue(callback.doneFlags.get(callback.doneFlags.size() - 1), "closing the sink is the completion signal"); + assertEquals(10, callback.lastBytesWritten); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ProgressResponseBodyTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ProgressResponseBodyTest.java new file mode 100644 index 000000000000..ed06ce05a04f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/ProgressResponseBodyTest.java @@ -0,0 +1,59 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; +import okio.Buffer; +import okio.BufferedSource; +import org.junit.jupiter.api.Test; + +public class ProgressResponseBodyTest { + + private static class RecordingCallback implements ApiCallback { + final List doneFlags = new ArrayList<>(); + long lastBytesRead = -1; + + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + } + + @Override + public void onSuccess(Object result, int statusCode, Map> responseHeaders) { + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + doneFlags.add(done); + lastBytesRead = bytesRead; + } + } + + @Test + public void completionIsReportedOnceEvenWhenTheExhaustedSourceIsReadAgain() throws IOException { + RecordingCallback callback = new RecordingCallback(); + ProgressResponseBody body = new ProgressResponseBody( + ResponseBody.create("hello", MediaType.get("text/plain")), callback); + + BufferedSource source = body.source(); + assertEquals("hello", source.readUtf8()); + // an exhausted source answers -1 again for every further read + assertEquals(-1, source.read(new Buffer(), 1)); + assertEquals(-1, source.read(new Buffer(), 1)); + assertTrue(source.exhausted()); + + long completions = callback.doneFlags.stream().filter(done -> done).count(); + assertEquals(1, completions, "done must be reported exactly once: " + callback.doneFlags); + assertTrue(callback.doneFlags.get(callback.doneFlags.size() - 1), "the terminal event comes last"); + assertEquals(5, callback.lastBytesRead); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/StringUtilTest.java new file mode 100644 index 000000000000..c946674e470a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.*; + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java new file mode 100644 index 000000000000..face3d9b785e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java @@ -0,0 +1,73 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +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 AnotherFakeApi + */ +@Disabled +public class AnotherFakeApiTest { + + private final AnotherFakeApi api = new AnotherFakeApi(); + + /** + * To test special tags + * + * To test special tags and operation ID starting with number + * + * @throws ApiException if the Api call fails + */ + @Test + public void call123testSpecialTagsTest() throws ApiException { + Client client = null; + Client response = api.call123testSpecialTags(client); + // TODO: test validations + } + + /** + * parameter array number default value + * + * @throws ApiException if the Api call fails + */ + @Test + public void getParameterArrayNumberTest() throws ApiException { + List array = null; + api.getParameterArrayNumber(array); + // TODO: test validations + } + + /** + * parameter string number + * + * @throws ApiException if the Api call fails + */ + @Test + public void getParameterStringNumberTest() throws ApiException { + BigDecimal stringNumber = null; + api.getParameterStringNumber(stringNumber); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/DefaultApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/DefaultApiTest.java new file mode 100644 index 000000000000..9dbc195b0857 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/DefaultApiTest.java @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.FakeAnyOfWIthSameErasureGet200Response; +import org.openapitools.client.model.FakeOneOfWIthSameErasureGet200Response; +import org.openapitools.client.model.FooGetDefaultResponse; +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 DefaultApi + */ +@Disabled +public class DefaultApiTest { + + private final DefaultApi api = new DefaultApi(); + + /** + * Test route, this shouldn't cause a compiler error + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeAnyOfWIthSameErasureGetTest() throws ApiException { + FakeAnyOfWIthSameErasureGet200Response response = api.fakeAnyOfWIthSameErasureGet(); + // TODO: test validations + } + + /** + * @throws ApiException if the Api call fails + */ + @Test + public void fakeFreeFormQueryParametersGetTest() throws ApiException { + String fixed = null; + Object freeForm = null; + api.fakeFreeFormQueryParametersGet(fixed, freeForm); + // TODO: test validations + } + + /** + * Test route, this shouldn't cause a compiler error + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeOneOfWIthSameErasureGetTest() throws ApiException { + FakeOneOfWIthSameErasureGet200Response response = api.fakeOneOfWIthSameErasureGet(); + // TODO: test validations + } + + /** + * @throws ApiException if the Api call fails + */ + @Test + public void fooGetTest() throws ApiException { + FooGetDefaultResponse response = api.fooGet(); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/FakeApiTest.java new file mode 100644 index 000000000000..095dfdcd2304 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -0,0 +1,395 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import org.openapitools.client.model.FakeRefParameterPetIdParameter; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.FreeFormObjectTestClass; +import org.openapitools.client.model.HealthCheckResult; +import java.time.LocalDate; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.NullableFieldsMapResponse; +import java.time.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.RequiredNullableBody; +import org.openapitools.client.model.TestInlineFreeformAdditionalPropertiesRequest; +import org.openapitools.client.model.User; +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 FakeApi + */ +@Disabled +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + /** + * Get a free form object or Json string + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeGetFreeFormObjectGetTest() throws ApiException { + FreeFormObjectTestClass response = api.fakeGetFreeFormObjectGet(); + // TODO: test validations + } + + /** + * Test serialization of outer boolean types + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeOuterBooleanSerializeTest() throws ApiException { + Boolean body = null; + Boolean response = api.fakeOuterBooleanSerialize(body); + // TODO: test validations + } + + /** + * Test serialization of object with outer number type + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeOuterCompositeSerializeTest() throws ApiException { + OuterComposite outerComposite = null; + OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite); + // TODO: test validations + } + + /** + * Test serialization of outer number types + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeOuterNumberSerializeTest() throws ApiException { + BigDecimal body = null; + BigDecimal response = api.fakeOuterNumberSerialize(body); + // TODO: test validations + } + + /** + * Test serialization of outer string types + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeOuterStringSerializeTest() throws ApiException { + String body = null; + String response = api.fakeOuterStringSerialize(body); + // TODO: test validations + } + + /** + * fake reference parameter + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeRefParameterTest() throws ApiException { + FakeRefParameterPetIdParameter petId = null; + api.fakeRefParameter(petId); + // TODO: test validations + } + + /** + * fields in the response body, required and nullable are both true + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeRequiredNullableBodyGetTest() throws ApiException { + RequiredNullableBody response = api.fakeRequiredNullableBodyGet(); + // TODO: test validations + } + + /** + * fake reference parameter + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void fakeUploadRefRequestBodiesTest() throws ApiException { + Long petId = null; + String additionalMetadata = null; + File _file = null; + ModelApiResponse response = api.fakeUploadRefRequestBodies(petId, additionalMetadata, _file); + // TODO: test validations + } + + /** + * Array of Enums + * + * @throws ApiException if the Api call fails + */ + @Test + public void getFakeArrayofenumsTest() throws ApiException { + List response = api.getFakeArrayofenums(); + // TODO: test validations + } + + /** + * Health check endpoint + * + * @throws ApiException if the Api call fails + */ + @Test + public void getFakeHealthTest() throws ApiException { + HealthCheckResult response = api.getFakeHealth(); + // TODO: test validations + } + + /** + * parameter name mapping test + * + * @throws ApiException if the Api call fails + */ + @Test + public void getParameterNameMappingTest() throws ApiException { + Long underscoreType = null; + String type = null; + String typeWithUnderscore = null; + api.getParameterNameMapping(underscoreType, type, typeWithUnderscore); + // TODO: test validations + } + + /** + * test referenced additionalProperties + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void testAdditionalPropertiesReferenceTest() throws ApiException { + Map requestBody = null; + api.testAdditionalPropertiesReference(requestBody); + // TODO: test validations + } + + /** + * For this test, the body for this request much reference a schema named `File`. + * + * @throws ApiException if the Api call fails + */ + @Test + public void testBodyWithFileSchemaTest() throws ApiException { + FileSchemaTestClass fileSchemaTestClass = null; + api.testBodyWithFileSchema(fileSchemaTestClass); + // TODO: test validations + } + + /** + * @throws ApiException if the Api call fails + */ + @Test + public void testBodyWithQueryParamsTest() throws ApiException { + String query = null; + User user = null; + api.testBodyWithQueryParams(query, user); + // TODO: test validations + } + + /** + * To test \"client\" model + * + * To test \"client\" model + * + * @throws ApiException if the Api call fails + */ + @Test + public void testClientModelTest() throws ApiException { + Client client = null; + Client response = api.testClientModel(client); + // TODO: test validations + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String patternWithoutDelimiter = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + String string = null; + File binary = null; + LocalDate date = null; + OffsetDateTime dateTime = null; + String password = null; + String paramCallback = null; + api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + // TODO: test validations + } + + /** + * To test enum parameters + * + * To test enum parameters + * + * @throws ApiException if the Api call fails + */ + @Test + public void testEnumParametersTest() throws ApiException { + List enumHeaderStringArray = null; + String enumHeaderString = null; + List enumQueryStringArray = null; + String enumQueryString = null; + Integer enumQueryInteger = null; + Double enumQueryDouble = null; + List enumFormStringArray = null; + String enumFormString = null; + api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + // TODO: test validations + } + + /** + * Fake endpoint to test group parameters (optional) + * + * Fake endpoint to test group parameters (optional) + * + * @throws ApiException if the Api call fails + */ + @Test + public void testGroupParametersTest() throws ApiException { + Integer requiredStringGroup = null; + Boolean requiredBooleanGroup = null; + Long requiredInt64Group = null; + Integer stringGroup = null; + Boolean booleanGroup = null; + Long int64Group = null; + api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) + .stringGroup(stringGroup) + .booleanGroup(booleanGroup) + .int64Group(int64Group) + .execute(); + // TODO: test validations + } + + /** + * test inline additionalProperties + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void testInlineAdditionalPropertiesTest() throws ApiException { + Map requestBody = null; + api.testInlineAdditionalProperties(requestBody); + // TODO: test validations + } + + /** + * test inline free-form additionalProperties + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void testInlineFreeformAdditionalPropertiesTest() throws ApiException { + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = null; + api.testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest); + // TODO: test validations + } + + /** + * test json serialization of form data + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void testJsonFormDataTest() throws ApiException { + String param = null; + String param2 = null; + api.testJsonFormData(param, param2); + // TODO: test validations + } + + /** + * test anyOf with map of objects containing nullable required fields + * + * Tests that anyOf deserialization works when object values contain required fields that are nullable (e.g. Record<string, { before: string | null, after: string | null }>) + * + * @throws ApiException if the Api call fails + */ + @Test + public void testNullableRequiredFieldsAnyOfTest() throws ApiException { + NullableFieldsMapResponse response = api.testNullableRequiredFieldsAnyOf(); + // TODO: test validations + } + + /** + * To test the collection format in query parameters + * + * @throws ApiException if the Api call fails + */ + @Test + public void testQueryParameterCollectionFormatTest() throws ApiException { + List pipe = null; + List ioutil = null; + List http = null; + List url = null; + List context = null; + api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + // TODO: test validations + } + + /** + * test referenced string map + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void testStringMapReferenceTest() throws ApiException { + Map requestBody = null; + api.testStringMapReference(requestBody); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java new file mode 100644 index 000000000000..aa1b824dd5a2 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java @@ -0,0 +1,48 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Client; +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 FakeClassnameTags123Api + */ +@Disabled +public class FakeClassnameTags123ApiTest { + + private final FakeClassnameTags123Api api = new FakeClassnameTags123Api(); + + /** + * To test class name in snake case + * + * To test class name in snake case + * + * @throws ApiException if the Api call fails + */ + @Test + public void testClassnameTest() throws ApiException { + Client client = null; + Client response = api.testClassname(client); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 000000000000..a1d3d6377d68 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +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 PetApi + */ +@Disabled +public class PetApiTest { + + private final PetApi api = new PetApi(); + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void addPetTest() throws ApiException { + Pet pet = null; + api.addPet(pet); + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void deletePetTest() throws ApiException { + Long petId = null; + String apiKey = null; + api.deletePet(petId, apiKey); + // TODO: test validations + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException if the Api call fails + */ + @Test + public void findPetsByStatusTest() throws ApiException { + List status = null; + List response = api.findPetsByStatus(status); + // TODO: test validations + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException if the Api call fails + */ + @Test + public void findPetsByTagsTest() throws ApiException { + List tags = null; + List response = api.findPetsByTags(tags); + // TODO: test validations + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException if the Api call fails + */ + @Test + public void getPetByIdTest() throws ApiException { + Long petId = null; + Pet response = api.getPetById(petId); + // TODO: test validations + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void updatePetTest() throws ApiException { + Pet pet = null; + api.updatePet(pet); + // TODO: test validations + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void updatePetWithFormTest() throws ApiException { + Long petId = null; + String name = null; + String status = null; + api.updatePetWithForm(petId, name, status); + // TODO: test validations + } + + /** + * uploads an image + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void uploadFileTest() throws ApiException { + Long petId = null; + String contentType = null; + String additionalMetadata = null; + File _file = null; + ModelApiResponse response = api.uploadFile(petId, contentType, additionalMetadata, _file); + // TODO: test validations + } + + /** + * uploads an image (required) + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void uploadFileWithRequiredFileTest() throws ApiException { + Long petId = null; + File requiredFile = null; + String additionalMetadata = null; + ModelApiResponse response = api.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/StoreApiTest.java new file mode 100644 index 000000000000..98354ba10c08 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/StoreApiTest.java @@ -0,0 +1,89 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Order; +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 StoreApi + */ +@Disabled +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException if the Api call fails + */ + @Test + public void deleteOrderTest() throws ApiException { + String orderId = null; + api.deleteOrder(orderId); + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException if the Api call fails + */ + @Test + public void getInventoryTest() throws ApiException { + Map response = api.getInventory(); + // TODO: test validations + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * + * @throws ApiException if the Api call fails + */ + @Test + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + Order response = api.getOrderById(orderId); + // TODO: test validations + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order order = null; + Order response = api.placeOrder(order); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/UserApiTest.java new file mode 100644 index 000000000000..aa9aff49b4df --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/UserApiTest.java @@ -0,0 +1,148 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.time.OffsetDateTime; +import org.openapitools.client.model.User; +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 UserApi + */ +@Disabled +public class UserApiTest { + + private final UserApi api = new UserApi(); + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException if the Api call fails + */ + @Test + public void createUserTest() throws ApiException { + User user = null; + api.createUser(user); + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws ApiException { + List user = null; + api.createUsersWithArrayInput(user); + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws ApiException { + List user = null; + api.createUsersWithListInput(user); + // TODO: test validations + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException if the Api call fails + */ + @Test + public void deleteUserTest() throws ApiException { + String username = null; + api.deleteUser(username); + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void getUserByNameTest() throws ApiException { + String username = null; + User response = api.getUserByName(username); + // TODO: test validations + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + String username = null; + String password = null; + String response = api.loginUser(username, password); + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void logoutUserTest() throws ApiException { + api.logoutUser(); + // TODO: test validations + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException if the Api call fails + */ + @Test + public void updateUserTest() throws ApiException { + String username = null; + User user = null; + api.updateUser(username, user); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/ValuesApiTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/ValuesApiTest.java new file mode 100644 index 000000000000..89a1ad0febc4 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/api/ValuesApiTest.java @@ -0,0 +1,47 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Variable; +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 ValuesApi + */ +@Disabled +public class ValuesApiTest { + + private final ValuesApi api = new ValuesApi(); + + /** + * Get some primitive variable values + * + * + * + * @throws ApiException if the Api call fails + */ + @Test + public void getSomeValuesTest() throws ApiException { + Variable response = api.getSomeValues(); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..c4b8362967d0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,119 @@ +package org.openapitools.client.auth; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header or cookie parameters + assertEquals(0, headerParams.size()); + assertEquals(0, cookieParams.size()); + } + + @Test + public void testApplyToParamsInQueryWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + assertEquals(0, cookieParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or cookie parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInHeaderWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInCookieWithPrefix() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or header parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + assertEquals(1, cookieParams.size()); + assertEquals("Token my-api-token", cookieParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInCookieWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..85b507f3e4b6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,78 @@ +package org.openapitools.client.auth; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @BeforeEach + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or cookie parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " + // prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + + // null username and password should be ignored + queryParams = new ArrayList(); + headerParams = new HashMap(); + auth.setUsername(null); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } + + @Test + public void credentialsOutsideLatin1AreEncodedAsUtf8() throws ApiException { + Map headerParams = new HashMap(); + + auth.setUsername("jürgen"); + auth.setPassword("пароль€"); + auth.applyToParams(new ArrayList(), headerParams, new HashMap(), null, null, null); + + String expected = "Basic " + java.util.Base64.getEncoder().encodeToString( + "jürgen:пароль€".getBytes(java.nio.charset.StandardCharsets.UTF_8)); + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java new file mode 100644 index 000000000000..32cd0bedbac8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java @@ -0,0 +1,223 @@ +package org.openapitools.client.auth; + +import static org.junit.jupiter.api.Assertions.*; + +import com.sun.net.httpserver.HttpServer; + +import java.io.IOException; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetSocketAddress; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +import okhttp3.FormBody; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * The okhttp library's RetryingOAuth was rewritten without Apache Oltu: it now builds its own + * token request via the {@link RetryingOAuth.TokenRequestBuilder} inner class and no longer + * exposes an {@code OAuthClient}/{@code OAuthOkHttpClient} seam to mock. Since this sample has + * no mocking library available, this test exercises the interceptor's retry-once behavior (and + * the token request it builds) against a real, local HTTP server instead of a mocked chain. + */ +public class RetryingOAuthTest { + + private HttpServer server; + private String baseUrl; + private RetryingOAuth oauth; + private OkHttpClient httpClient; + private final AtomicInteger tokenRequests = new AtomicInteger(); + + @BeforeEach + public void setUp() throws Exception { + server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); + server.setExecutor(Executors.newCachedThreadPool()); + + // Token endpoint: always issues "new-access-token". + server.createContext("/token", exchange -> { + tokenRequests.incrementAndGet(); + try { + // small delay so two concurrent 401s are likely to overlap on the + // synchronized updateAccessToken() critical section + Thread.sleep(300); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + byte[] body = "{\"access_token\":\"new-access-token\",\"token_type\":\"Bearer\"}" + .getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + + // Protected resource: 200 only when called with the fresh access token, 401 otherwise. + server.createContext("/api", exchange -> { + String authHeader = exchange.getRequestHeaders().getFirst("Authorization"); + String delay = exchange.getRequestHeaders().getFirst("X-Delay"); + if (delay != null) { + try { + Thread.sleep(Long.parseLong(delay)); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + } + int code = "Bearer new-access-token".equals(authHeader) + ? HttpURLConnection.HTTP_OK + : HttpURLConnection.HTTP_UNAUTHORIZED; + exchange.sendResponseHeaders(code, -1); + exchange.close(); + }); + + // Token endpoints that misbehave: an OAuth error response, and a 2xx body that is not JSON. + server.createContext("/token-error", exchange -> { + byte[] body = "{\"error\":\"invalid_client\"}".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/json"); + exchange.sendResponseHeaders(HttpURLConnection.HTTP_BAD_REQUEST, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + server.createContext("/token-form", exchange -> { + byte[] body = "access_token=abc&token_type=Bearer".getBytes(StandardCharsets.UTF_8); + exchange.getResponseHeaders().add("Content-Type", "application/x-www-form-urlencoded"); + exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, body.length); + try (OutputStream os = exchange.getResponseBody()) { + os.write(body); + } + }); + + server.start(); + int port = server.getAddress().getPort(); + baseUrl = "http://127.0.0.1:" + port; + + oauth = new RetryingOAuth( + baseUrl + "/token", + "_clientId", + OAuthFlow.ACCESS_CODE, + "_clientSecret", + Collections.emptyMap()); + oauth.setAccessToken("expired-access-token"); + + httpClient = new OkHttpClient.Builder().addInterceptor(oauth).build(); + } + + @AfterEach + public void tearDown() { + server.stop(0); + } + + @Test + public void testSingleRequestUnauthorized() throws Exception { + try (Response response = httpClient.newCall(new Request.Builder().url(baseUrl + "/api").build()).execute()) { + assertEquals(HttpURLConnection.HTTP_OK, response.code()); + } + } + + @Test + public void testTwoConcurrentRequestsUnauthorized() throws Exception { + Callable callable = () -> { + try (Response response = httpClient.newCall(new Request.Builder().url(baseUrl + "/api").build()).execute()) { + return response.code(); + } + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future response1 = executor.submit(callable); + Future response2 = executor.submit(callable); + + assertEquals(HttpURLConnection.HTTP_OK, response1.get(10, TimeUnit.SECONDS).intValue()); + assertEquals(HttpURLConnection.HTTP_OK, response2.get(10, TimeUnit.SECONDS).intValue()); + } finally { + executor.shutdown(); + } + } + + @Test + public void testTokenRequestBuilderIncludesGrantTypeAndCredentials() throws Exception { + Request tokenRequest = oauth.getTokenRequestBuilder().build(); + assertEquals(baseUrl + "/token", tokenRequest.url().toString()); + assertEquals("POST", tokenRequest.method()); + + okhttp3.RequestBody body = tokenRequest.body(); + assertNotNull(body); + assertTrue(body instanceof FormBody); + FormBody formBody = (FormBody) body; + Map formParams = new HashMap<>(); + for (int i = 0; i < formBody.size(); i++) { + formParams.put(formBody.encodedName(i), formBody.encodedValue(i)); + } + + // setFlow(OAuthFlow.ACCESS_CODE) (via the constructor) maps to "authorization_code" + assertEquals("authorization_code", formParams.get("grant_type")); + assertEquals("_clientId", formParams.get("client_id")); + assertEquals("_clientSecret", formParams.get("client_secret")); + } + + @Test + public void testStaleTokenIsRefreshedOnlyOnce() throws Exception { + // The second request's 401 arrives only after the first request has already refreshed the + // token; it must reuse the refreshed token instead of asking the token endpoint again + // (and it must still be retried, i.e. end in 200). + Request fast = new Request.Builder().url(baseUrl + "/api").build(); + Request slow = new Request.Builder().url(baseUrl + "/api").header("X-Delay", "700").build(); + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future slowResponse = executor.submit(() -> { + try (Response response = httpClient.newCall(slow).execute()) { + return response.code(); + } + }); + Future fastResponse = executor.submit(() -> { + try (Response response = httpClient.newCall(fast).execute()) { + return response.code(); + } + }); + assertEquals(HttpURLConnection.HTTP_OK, fastResponse.get(10, TimeUnit.SECONDS).intValue()); + assertEquals(HttpURLConnection.HTTP_OK, slowResponse.get(10, TimeUnit.SECONDS).intValue()); + } finally { + executor.shutdown(); + } + assertEquals(1, tokenRequests.get(), "token endpoint must be called once per stale token, not once per 401"); + } + + @Test + public void testTokenEndpointErrorIsReported() { + RetryingOAuth failing = new RetryingOAuth(baseUrl + "/token-error", "_clientId", OAuthFlow.ACCESS_CODE, + "_clientSecret", Collections.emptyMap()); + OkHttpClient client = new OkHttpClient.Builder().addInterceptor(failing).build(); + + IOException e = assertThrows(IOException.class, + () -> client.newCall(new Request.Builder().url(baseUrl + "/api").build()).execute()); + assertTrue(e.getMessage().contains("400"), e.getMessage()); + assertTrue(e.getMessage().contains("invalid_client"), e.getMessage()); + assertNull(failing.getAccessToken()); + } + + @Test + public void testUnparseableTokenResponseIsReported() { + RetryingOAuth failing = new RetryingOAuth(baseUrl + "/token-form", "_clientId", OAuthFlow.ACCESS_CODE, + "_clientSecret", Collections.emptyMap()); + OkHttpClient client = new OkHttpClient.Builder().addInterceptor(failing).build(); + + IOException e = assertThrows(IOException.class, + () -> client.newCall(new Request.Builder().url(baseUrl + "/api").build()).execute()); + assertTrue(e.getMessage().contains("could not be parsed") || e.getMessage().contains("no access_token"), e.getMessage()); + assertNull(failing.getAccessToken()); + } +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java new file mode 100644 index 000000000000..528fed5d86aa --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java @@ -0,0 +1,97 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AdditionalPropertiesClass + */ +public class AdditionalPropertiesClassTest { + private final AdditionalPropertiesClass model = new AdditionalPropertiesClass(); + + /** + * Model tests for AdditionalPropertiesClass + */ + @Test + public void testAdditionalPropertiesClass() { + // TODO: test AdditionalPropertiesClass + } + + /** + * Test the property 'mapProperty' + */ + @Test + public void mapPropertyTest() { + // TODO: test mapProperty + } + + /** + * Test the property 'mapOfMapProperty' + */ + @Test + public void mapOfMapPropertyTest() { + // TODO: test mapOfMapProperty + } + + /** + * Test the property 'anytype1' + */ + @Test + public void anytype1Test() { + // TODO: test anytype1 + } + + /** + * Test the property 'mapWithUndeclaredPropertiesAnytype1' + */ + @Test + public void mapWithUndeclaredPropertiesAnytype1Test() { + // TODO: test mapWithUndeclaredPropertiesAnytype1 + } + + /** + * Test the property 'mapWithUndeclaredPropertiesAnytype2' + */ + @Test + public void mapWithUndeclaredPropertiesAnytype2Test() { + // TODO: test mapWithUndeclaredPropertiesAnytype2 + } + + /** + * Test the property 'mapWithUndeclaredPropertiesAnytype3' + */ + @Test + public void mapWithUndeclaredPropertiesAnytype3Test() { + // TODO: test mapWithUndeclaredPropertiesAnytype3 + } + + /** + * Test the property 'emptyMap' + */ + @Test + public void emptyMapTest() { + // TODO: test emptyMap + } + + /** + * Test the property 'mapWithUndeclaredPropertiesString' + */ + @Test + public void mapWithUndeclaredPropertiesStringTest() { + // TODO: test mapWithUndeclaredPropertiesString + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesCTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesCTest.java new file mode 100644 index 000000000000..d22c41f8e4b6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesCTest.java @@ -0,0 +1,113 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfAttributesC + */ +public class AllOfModelArrayAnyOfAllOfAttributesCTest { + private final AllOfModelArrayAnyOfAllOfAttributesC model = new AllOfModelArrayAnyOfAllOfAttributesC(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfAttributesC + */ + @Test + public void testAllOfModelArrayAnyOfAllOfAttributesC() { + // TODO: test AllOfModelArrayAnyOfAllOfAttributesC + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesTest.java new file mode 100644 index 000000000000..c9a28a5883aa --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfAttributes + */ +public class AllOfModelArrayAnyOfAllOfAttributesTest { + private final AllOfModelArrayAnyOfAllOfAttributes model = new AllOfModelArrayAnyOfAllOfAttributes(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfAttributes + */ + @Test + public void testAllOfModelArrayAnyOfAllOfAttributes() { + // TODO: test AllOfModelArrayAnyOfAllOfAttributes + } + + /** + * Test the property 'C' + */ + @Test + public void CTest() { + // TODO: test C + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Test.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Test.java new file mode 100644 index 000000000000..5cdd9621336b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Test.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ +public class AllOfModelArrayAnyOfAllOfLinkListColumn1Test { + private final AllOfModelArrayAnyOfAllOfLinkListColumn1 model = new AllOfModelArrayAnyOfAllOfLinkListColumn1(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ + @Test + public void testAllOfModelArrayAnyOfAllOfLinkListColumn1() { + // TODO: test AllOfModelArrayAnyOfAllOfLinkListColumn1 + } + + /** + * Test the property 'value' + */ + @Test + public void valueTest() { + // TODO: test value + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest.java new file mode 100644 index 000000000000..1b7a4c0c2194 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest.java @@ -0,0 +1,137 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ +public class AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest { + private final AllOfModelArrayAnyOfAllOfLinkListColumn1Value model = new AllOfModelArrayAnyOfAllOfLinkListColumn1Value(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ + @Test + public void testAllOfModelArrayAnyOfAllOfLinkListColumn1Value() { + // TODO: test AllOfModelArrayAnyOfAllOfLinkListColumn1Value + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + + /** + * Test the property 'objectWithNoDeclaredProps' + */ + @Test + public void objectWithNoDeclaredPropsTest() { + // TODO: test objectWithNoDeclaredProps + } + + /** + * Test the property 'objectWithNoDeclaredPropsNullable' + */ + @Test + public void objectWithNoDeclaredPropsNullableTest() { + // TODO: test objectWithNoDeclaredPropsNullable + } + + /** + * Test the property 'anyTypeProp' + */ + @Test + public void anyTypePropTest() { + // TODO: test anyTypeProp + } + + /** + * Test the property 'anyTypePropNullable' + */ + @Test + public void anyTypePropNullableTest() { + // TODO: test anyTypePropNullable + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfTest.java new file mode 100644 index 000000000000..c7266faaa79b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOf + */ +public class AllOfModelArrayAnyOfTest { + private final AllOfModelArrayAnyOf model = new AllOfModelArrayAnyOf(); + + /** + * Model tests for AllOfModelArrayAnyOf + */ + @Test + public void testAllOfModelArrayAnyOf() { + // TODO: test AllOfModelArrayAnyOf + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'linkListColumn1' + */ + @Test + public void linkListColumn1Test() { + // TODO: test linkListColumn1 + } + + /** + * Test the property 'attributes' + */ + @Test + public void attributesTest() { + // TODO: test attributes + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToDoubleTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToDoubleTest.java new file mode 100644 index 000000000000..d881638d1c8f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToDoubleTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfRefToDouble + */ +public class AllOfRefToDoubleTest { + private final AllOfRefToDouble model = new AllOfRefToDouble(); + + /** + * Model tests for AllOfRefToDouble + */ + @Test + public void testAllOfRefToDouble() { + // TODO: test AllOfRefToDouble + } + + /** + * Test the property 'height' + */ + @Test + public void heightTest() { + // TODO: test height + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToFloatTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToFloatTest.java new file mode 100644 index 000000000000..efdf86999114 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToFloatTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfRefToFloat + */ +public class AllOfRefToFloatTest { + private final AllOfRefToFloat model = new AllOfRefToFloat(); + + /** + * Model tests for AllOfRefToFloat + */ + @Test + public void testAllOfRefToFloat() { + // TODO: test AllOfRefToFloat + } + + /** + * Test the property 'weight' + */ + @Test + public void weightTest() { + // TODO: test weight + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToLongTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToLongTest.java new file mode 100644 index 000000000000..65148202fbc6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AllOfRefToLongTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfRefToLong + */ +public class AllOfRefToLongTest { + private final AllOfRefToLong model = new AllOfRefToLong(); + + /** + * Model tests for AllOfRefToLong + */ + @Test + public void testAllOfRefToLong() { + // TODO: test AllOfRefToLong + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AnimalTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AnimalTest.java new file mode 100644 index 000000000000..8da0e95590f5 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AnimalTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Animal + */ +public class AnimalTest { + private final Animal model = new Animal(); + + /** + * Model tests for Animal + */ + @Test + public void testAnimal() { + // TODO: test Animal + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AppleReqTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AppleReqTest.java new file mode 100644 index 000000000000..c8926998f651 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AppleReqTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AppleReq + */ +public class AppleReqTest { + private final AppleReq model = new AppleReq(); + + /** + * Model tests for AppleReq + */ + @Test + public void testAppleReq() { + // TODO: test AppleReq + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'mealy' + */ + @Test + public void mealyTest() { + // TODO: test mealy + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AppleTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AppleTest.java new file mode 100644 index 000000000000..6a517df1d794 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/AppleTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Apple + */ +public class AppleTest { + private final Apple model = new Apple(); + + /** + * Model tests for Apple + */ + @Test + public void testApple() { + // TODO: test Apple + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'origin' + */ + @Test + public void originTest() { + // TODO: test origin + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayAnyOfTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayAnyOfTest.java new file mode 100644 index 000000000000..0461bc83a106 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayAnyOfTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayAnyOf + */ +public class ArrayAnyOfTest { + private final ArrayAnyOf model = new ArrayAnyOf(); + + /** + * Model tests for ArrayAnyOf + */ + @Test + public void testArrayAnyOf() { + // TODO: test ArrayAnyOf + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayDefaultTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayDefaultTest.java new file mode 100644 index 000000000000..411bd9e34733 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayDefaultTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayDefault + */ +public class ArrayDefaultTest { + private final ArrayDefault model = new ArrayDefault(); + + /** + * Model tests for ArrayDefault + */ + @Test + public void testArrayDefault() { + // TODO: test ArrayDefault + } + + /** + * Test the property 'withDefaultEmptyBracket' + */ + @Test + public void withDefaultEmptyBracketTest() { + // TODO: test withDefaultEmptyBracket + } + + /** + * Test the property 'withoutDefault' + */ + @Test + public void withoutDefaultTest() { + // TODO: test withoutDefault + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java new file mode 100644 index 000000000000..f1a2bae967bf --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayOfArrayOfNumberOnly + */ +public class ArrayOfArrayOfNumberOnlyTest { + private final ArrayOfArrayOfNumberOnly model = new ArrayOfArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfArrayOfNumberOnly + */ + @Test + public void testArrayOfArrayOfNumberOnly() { + // TODO: test ArrayOfArrayOfNumberOnly + } + + /** + * Test the property 'arrayArrayNumber' + */ + @Test + public void arrayArrayNumberTest() { + // TODO: test arrayArrayNumber + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest.java new file mode 100644 index 000000000000..b5ebba504779 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayOfInlineAllOfArrayAllofDogPropertyInner + */ +public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest { + private final ArrayOfInlineAllOfArrayAllofDogPropertyInner model = new ArrayOfInlineAllOfArrayAllofDogPropertyInner(); + + /** + * Model tests for ArrayOfInlineAllOfArrayAllofDogPropertyInner + */ + @Test + public void testArrayOfInlineAllOfArrayAllofDogPropertyInner() { + // TODO: test ArrayOfInlineAllOfArrayAllofDogPropertyInner + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfTest.java new file mode 100644 index 000000000000..489e396ba1f9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayOfInlineAllOf + */ +public class ArrayOfInlineAllOfTest { + private final ArrayOfInlineAllOf model = new ArrayOfInlineAllOf(); + + /** + * Model tests for ArrayOfInlineAllOf + */ + @Test + public void testArrayOfInlineAllOf() { + // TODO: test ArrayOfInlineAllOf + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'arrayAllofDogProperty' + */ + @Test + public void arrayAllofDogPropertyTest() { + // TODO: test arrayAllofDogProperty + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java new file mode 100644 index 000000000000..fea0520c68c6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayOfNumberOnly + */ +public class ArrayOfNumberOnlyTest { + private final ArrayOfNumberOnly model = new ArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfNumberOnly + */ + @Test + public void testArrayOfNumberOnly() { + // TODO: test ArrayOfNumberOnly + } + + /** + * Test the property 'arrayNumber' + */ + @Test + public void arrayNumberTest() { + // TODO: test arrayNumber + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOneOfTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOneOfTest.java new file mode 100644 index 000000000000..5bcb5468092c --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayOneOfTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayOneOf + */ +public class ArrayOneOfTest { + private final ArrayOneOf model = new ArrayOneOf(); + + /** + * Model tests for ArrayOneOf + */ + @Test + public void testArrayOneOf() { + // TODO: test ArrayOneOf + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayTestTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayTestTest.java new file mode 100644 index 000000000000..0284afe0bc35 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ArrayTestTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ArrayTest + */ +public class ArrayTestTest { + private final ArrayTest model = new ArrayTest(); + + /** + * Model tests for ArrayTest + */ + @Test + public void testArrayTest() { + // TODO: test ArrayTest + } + + /** + * Test the property 'arrayOfString' + */ + @Test + public void arrayOfStringTest() { + // TODO: test arrayOfString + } + + /** + * Test the property 'arrayArrayOfInteger' + */ + @Test + public void arrayArrayOfIntegerTest() { + // TODO: test arrayArrayOfInteger + } + + /** + * Test the property 'arrayArrayOfModel' + */ + @Test + public void arrayArrayOfModelTest() { + // TODO: test arrayArrayOfModel + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BananaReqTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BananaReqTest.java new file mode 100644 index 000000000000..84df07da33ed --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BananaReqTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for BananaReq + */ +public class BananaReqTest { + private final BananaReq model = new BananaReq(); + + /** + * Model tests for BananaReq + */ + @Test + public void testBananaReq() { + // TODO: test BananaReq + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + + /** + * Test the property 'sweet' + */ + @Test + public void sweetTest() { + // TODO: test sweet + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BananaTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BananaTest.java new file mode 100644 index 000000000000..0070b4cf4afc --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BananaTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Banana + */ +public class BananaTest { + private final Banana model = new Banana(); + + /** + * Model tests for Banana + */ + @Test + public void testBanana() { + // TODO: test Banana + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BasquePigTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BasquePigTest.java new file mode 100644 index 000000000000..cee9dbb31ec4 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/BasquePigTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for BasquePig + */ +public class BasquePigTest { + private final BasquePig model = new BasquePig(); + + /** + * Model tests for BasquePig + */ + @Test + public void testBasquePig() { + // TODO: test BasquePig + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CapitalizationTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CapitalizationTest.java new file mode 100644 index 000000000000..4cf43ca42492 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CapitalizationTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Capitalization + */ +public class CapitalizationTest { + private final Capitalization model = new Capitalization(); + + /** + * Model tests for Capitalization + */ + @Test + public void testCapitalization() { + // TODO: test Capitalization + } + + /** + * Test the property 'smallCamel' + */ + @Test + public void smallCamelTest() { + // TODO: test smallCamel + } + + /** + * Test the property 'capitalCamel' + */ + @Test + public void capitalCamelTest() { + // TODO: test capitalCamel + } + + /** + * Test the property 'smallSnake' + */ + @Test + public void smallSnakeTest() { + // TODO: test smallSnake + } + + /** + * Test the property 'capitalSnake' + */ + @Test + public void capitalSnakeTest() { + // TODO: test capitalSnake + } + + /** + * Test the property 'scAETHFlowPoints' + */ + @Test + public void scAETHFlowPointsTest() { + // TODO: test scAETHFlowPoints + } + + /** + * Test the property 'ATT_NAME' + */ + @Test + public void ATT_NAMETest() { + // TODO: test ATT_NAME + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CatTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CatTest.java new file mode 100644 index 000000000000..22b1e0111645 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CatTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Cat + */ +public class CatTest { + private final Cat model = new Cat(); + + /** + * Model tests for Cat + */ + @Test + public void testCat() { + // TODO: test Cat + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 000000000000..74ed3e42bc69 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ClassModelTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ClassModelTest.java new file mode 100644 index 000000000000..799b6c848094 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ClassModelTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ClassModel + */ +public class ClassModelTest { + private final ClassModel model = new ClassModel(); + + /** + * Model tests for ClassModel + */ + @Test + public void testClassModel() { + // TODO: test ClassModel + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ClientTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ClientTest.java new file mode 100644 index 000000000000..60ec6cc09093 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ClientTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Client + */ +public class ClientTest { + private final Client model = new Client(); + + /** + * Model tests for Client + */ + @Test + public void testClient() { + // TODO: test Client + } + + /** + * Test the property 'client' + */ + @Test + public void clientTest() { + // TODO: test client + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java new file mode 100644 index 000000000000..88acd6f1f749 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ComplexQuadrilateral + */ +public class ComplexQuadrilateralTest { + private final ComplexQuadrilateral model = new ComplexQuadrilateral(); + + /** + * Model tests for ComplexQuadrilateral + */ + @Test + public void testComplexQuadrilateral() { + // TODO: test ComplexQuadrilateral + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DanishPigTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DanishPigTest.java new file mode 100644 index 000000000000..327d37e158f7 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DanishPigTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for DanishPig + */ +public class DanishPigTest { + private final DanishPig model = new DanishPig(); + + /** + * Model tests for DanishPig + */ + @Test + public void testDanishPig() { + // TODO: test DanishPig + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java new file mode 100644 index 000000000000..b3db962b0727 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for DeprecatedObject + */ +public class DeprecatedObjectTest { + private final DeprecatedObject model = new DeprecatedObject(); + + /** + * Model tests for DeprecatedObject + */ + @Test + public void testDeprecatedObject() { + // TODO: test DeprecatedObject + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DogTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DogTest.java new file mode 100644 index 000000000000..3158d1bd793d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DogTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Dog + */ +public class DogTest { + private final Dog model = new Dog(); + + /** + * Model tests for Dog + */ + @Test + public void testDog() { + // TODO: test Dog + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DrawingTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DrawingTest.java new file mode 100644 index 000000000000..62f8b186f76c --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/DrawingTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Drawing + */ +public class DrawingTest { + private final Drawing model = new Drawing(); + + /** + * Model tests for Drawing + */ + @Test + public void testDrawing() { + // TODO: test Drawing + } + + /** + * Test the property 'mainShape' + */ + @Test + public void mainShapeTest() { + // TODO: test mainShape + } + + /** + * Test the property 'shapeOrNull' + */ + @Test + public void shapeOrNullTest() { + // TODO: test shapeOrNull + } + + /** + * Test the property 'nullableShape' + */ + @Test + public void nullableShapeTest() { + // TODO: test nullableShape + } + + /** + * Test the property 'shapes' + */ + @Test + public void shapesTest() { + // TODO: test shapes + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumArraysTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumArraysTest.java new file mode 100644 index 000000000000..9383748385db --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumArraysTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for EnumArrays + */ +public class EnumArraysTest { + private final EnumArrays model = new EnumArrays(); + + /** + * Model tests for EnumArrays + */ + @Test + public void testEnumArrays() { + // TODO: test EnumArrays + } + + /** + * Test the property 'justSymbol' + */ + @Test + public void justSymbolTest() { + // TODO: test justSymbol + } + + /** + * Test the property 'arrayEnum' + */ + @Test + public void arrayEnumTest() { + // TODO: test arrayEnum + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumClassTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumClassTest.java new file mode 100644 index 000000000000..6896bb0a4e90 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumClassTest.java @@ -0,0 +1,31 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for EnumClass + */ +public class EnumClassTest { + /** + * Model tests for EnumClass + */ + @Test + public void testEnumClass() { + // TODO: test EnumClass + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java new file mode 100644 index 000000000000..cbd97964fdcf --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for EnumStringDiscriminator + */ +public class EnumStringDiscriminatorTest { + private final EnumStringDiscriminator model = new EnumStringDiscriminator(); + + /** + * Model tests for EnumStringDiscriminator + */ + @Test + public void testEnumStringDiscriminator() { + // TODO: test EnumStringDiscriminator + } + + /** + * Test the property 'enumStrType' + */ + @Test + public void enumStrTypeTest() { + // TODO: test enumStrType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumTestTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumTestTest.java new file mode 100644 index 000000000000..38d573f5c47f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EnumTestTest.java @@ -0,0 +1,105 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for EnumTest + */ +public class EnumTestTest { + private final EnumTest model = new EnumTest(); + + /** + * Model tests for EnumTest + */ + @Test + public void testEnumTest() { + // TODO: test EnumTest + } + + /** + * Test the property 'enumString' + */ + @Test + public void enumStringTest() { + // TODO: test enumString + } + + /** + * Test the property 'enumStringRequired' + */ + @Test + public void enumStringRequiredTest() { + // TODO: test enumStringRequired + } + + /** + * Test the property 'enumInteger' + */ + @Test + public void enumIntegerTest() { + // TODO: test enumInteger + } + + /** + * Test the property 'enumIntegerOnly' + */ + @Test + public void enumIntegerOnlyTest() { + // TODO: test enumIntegerOnly + } + + /** + * Test the property 'enumNumber' + */ + @Test + public void enumNumberTest() { + // TODO: test enumNumber + } + + /** + * Test the property 'outerEnum' + */ + @Test + public void outerEnumTest() { + // TODO: test outerEnum + } + + /** + * Test the property 'outerEnumInteger' + */ + @Test + public void outerEnumIntegerTest() { + // TODO: test outerEnumInteger + } + + /** + * Test the property 'outerEnumDefaultValue' + */ + @Test + public void outerEnumDefaultValueTest() { + // TODO: test outerEnumDefaultValue + } + + /** + * Test the property 'outerEnumIntegerDefaultValue' + */ + @Test + public void outerEnumIntegerDefaultValueTest() { + // TODO: test outerEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java new file mode 100644 index 000000000000..dfb81ec5a9a0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for EquilateralTriangle + */ +public class EquilateralTriangleTest { + private final EquilateralTriangle model = new EquilateralTriangle(); + + /** + * Model tests for EquilateralTriangle + */ + @Test + public void testEquilateralTriangle() { + // TODO: test EquilateralTriangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeAnyOfWIthSameErasureGet200ResponseTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeAnyOfWIthSameErasureGet200ResponseTest.java new file mode 100644 index 000000000000..7061a98b70e0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeAnyOfWIthSameErasureGet200ResponseTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FakeAnyOfWIthSameErasureGet200Response + */ +public class FakeAnyOfWIthSameErasureGet200ResponseTest { + private final FakeAnyOfWIthSameErasureGet200Response model = new FakeAnyOfWIthSameErasureGet200Response(); + + /** + * Model tests for FakeAnyOfWIthSameErasureGet200Response + */ + @Test + public void testFakeAnyOfWIthSameErasureGet200Response() { + // TODO: test FakeAnyOfWIthSameErasureGet200Response + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeOneOfWIthSameErasureGet200ResponseTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeOneOfWIthSameErasureGet200ResponseTest.java new file mode 100644 index 000000000000..016c8db6a052 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeOneOfWIthSameErasureGet200ResponseTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FakeOneOfWIthSameErasureGet200Response + */ +public class FakeOneOfWIthSameErasureGet200ResponseTest { + private final FakeOneOfWIthSameErasureGet200Response model = new FakeOneOfWIthSameErasureGet200Response(); + + /** + * Model tests for FakeOneOfWIthSameErasureGet200Response + */ + @Test + public void testFakeOneOfWIthSameErasureGet200Response() { + // TODO: test FakeOneOfWIthSameErasureGet200Response + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeRefParameterPetIdParameterTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeRefParameterPetIdParameterTest.java new file mode 100644 index 000000000000..5d6fca30c3e2 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FakeRefParameterPetIdParameterTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FakeRefParameterPetIdParameter + */ +public class FakeRefParameterPetIdParameterTest { + private final FakeRefParameterPetIdParameter model = new FakeRefParameterPetIdParameter(); + + /** + * Model tests for FakeRefParameterPetIdParameter + */ + @Test + public void testFakeRefParameterPetIdParameter() { + // TODO: test FakeRefParameterPetIdParameter + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java new file mode 100644 index 000000000000..f4960c16dbad --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FileSchemaTestClass + */ +public class FileSchemaTestClassTest { + private final FileSchemaTestClass model = new FileSchemaTestClass(); + + /** + * Model tests for FileSchemaTestClass + */ + @Test + public void testFileSchemaTestClass() { + // TODO: test FileSchemaTestClass + } + + /** + * Test the property '_file' + */ + @Test + public void _fileTest() { + // TODO: test _file + } + + /** + * Test the property 'files' + */ + @Test + public void filesTest() { + // TODO: test files + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java new file mode 100644 index 000000000000..05777cac524d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FooGetDefaultResponse + */ +public class FooGetDefaultResponseTest { + private final FooGetDefaultResponse model = new FooGetDefaultResponse(); + + /** + * Model tests for FooGetDefaultResponse + */ + @Test + public void testFooGetDefaultResponse() { + // TODO: test FooGetDefaultResponse + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FooTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FooTest.java new file mode 100644 index 000000000000..182c1c09264d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FooTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Foo + */ +public class FooTest { + private final Foo model = new Foo(); + + /** + * Model tests for Foo + */ + @Test + public void testFoo() { + // TODO: test Foo + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FormatTestTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FormatTestTest.java new file mode 100644 index 000000000000..03a996eda8f3 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FormatTestTest.java @@ -0,0 +1,169 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FormatTest + */ +public class FormatTestTest { + private final FormatTest model = new FormatTest(); + + /** + * Model tests for FormatTest + */ + @Test + public void testFormatTest() { + // TODO: test FormatTest + } + + /** + * Test the property 'integer' + */ + @Test + public void integerTest() { + // TODO: test integer + } + + /** + * Test the property 'int32' + */ + @Test + public void int32Test() { + // TODO: test int32 + } + + /** + * Test the property 'int64' + */ + @Test + public void int64Test() { + // TODO: test int64 + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + + /** + * Test the property 'decimal' + */ + @Test + public void decimalTest() { + // TODO: test decimal + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + + /** + * Test the property '_byte' + */ + @Test + public void _byteTest() { + // TODO: test _byte + } + + /** + * Test the property 'binary' + */ + @Test + public void binaryTest() { + // TODO: test binary + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'uuidWithDefault' + */ + @Test + public void uuidWithDefaultTest() { + // TODO: test uuidWithDefault + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'patternWithDigits' + */ + @Test + public void patternWithDigitsTest() { + // TODO: test patternWithDigits + } + + /** + * Test the property 'patternWithDigitsAndDelimiter' + */ + @Test + public void patternWithDigitsAndDelimiterTest() { + // TODO: test patternWithDigitsAndDelimiter + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassPropertiesTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassPropertiesTest.java new file mode 100644 index 000000000000..dac2da5abf1e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassPropertiesTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FreeFormObjectTestClassProperties + */ +public class FreeFormObjectTestClassPropertiesTest { + private final FreeFormObjectTestClassProperties model = new FreeFormObjectTestClassProperties(); + + /** + * Model tests for FreeFormObjectTestClassProperties + */ + @Test + public void testFreeFormObjectTestClassProperties() { + // TODO: test FreeFormObjectTestClassProperties + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassTest.java new file mode 100644 index 000000000000..9befe700f4e4 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FreeFormObjectTestClass + */ +public class FreeFormObjectTestClassTest { + private final FreeFormObjectTestClass model = new FreeFormObjectTestClass(); + + /** + * Model tests for FreeFormObjectTestClass + */ + @Test + public void testFreeFormObjectTestClass() { + // TODO: test FreeFormObjectTestClass + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'properties' + */ + @Test + public void propertiesTest() { + // TODO: test properties + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FruitReqTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FruitReqTest.java new file mode 100644 index 000000000000..78f791bb5bba --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FruitReqTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FruitReq + */ +public class FruitReqTest { + private final FruitReq model = new FruitReq(); + + /** + * Model tests for FruitReq + */ + @Test + public void testFruitReq() { + // TODO: test FruitReq + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'mealy' + */ + @Test + public void mealyTest() { + // TODO: test mealy + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + + /** + * Test the property 'sweet' + */ + @Test + public void sweetTest() { + // TODO: test sweet + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FruitTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FruitTest.java new file mode 100644 index 000000000000..1c6c5a24ffe8 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/FruitTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Fruit + */ +public class FruitTest { + private final Fruit model = new Fruit(); + + /** + * Model tests for Fruit + */ + @Test + public void testFruit() { + // TODO: test Fruit + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'origin' + */ + @Test + public void originTest() { + // TODO: test origin + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/GmFruitTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/GmFruitTest.java new file mode 100644 index 000000000000..9e1542c1dd25 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/GmFruitTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for GmFruit + */ +public class GmFruitTest { + private final GmFruit model = new GmFruit(); + + /** + * Model tests for GmFruit + */ + @Test + public void testGmFruit() { + // TODO: test GmFruit + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'origin' + */ + @Test + public void originTest() { + // TODO: test origin + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java new file mode 100644 index 000000000000..188613ba5620 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for GrandparentAnimal + */ +public class GrandparentAnimalTest { + private final GrandparentAnimal model = new GrandparentAnimal(); + + /** + * Model tests for GrandparentAnimal + */ + @Test + public void testGrandparentAnimal() { + // TODO: test GrandparentAnimal + } + + /** + * Test the property 'petType' + */ + @Test + public void petTypeTest() { + // TODO: test petType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java new file mode 100644 index 000000000000..e4508b243c66 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for HasOnlyReadOnly + */ +public class HasOnlyReadOnlyTest { + private final HasOnlyReadOnly model = new HasOnlyReadOnly(); + + /** + * Model tests for HasOnlyReadOnly + */ + @Test + public void testHasOnlyReadOnly() { + // TODO: test HasOnlyReadOnly + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java new file mode 100644 index 000000000000..930de0e5d265 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for HealthCheckResult + */ +public class HealthCheckResultTest { + private final HealthCheckResult model = new HealthCheckResult(); + + /** + * Model tests for HealthCheckResult + */ + @Test + public void testHealthCheckResult() { + // TODO: test HealthCheckResult + } + + /** + * Test the property 'nullableMessage' + */ + @Test + public void nullableMessageTest() { + // TODO: test nullableMessage + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java new file mode 100644 index 000000000000..43b43d6ff121 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for IsoscelesTriangle + */ +public class IsoscelesTriangleTest { + private final IsoscelesTriangle model = new IsoscelesTriangle(); + + /** + * Model tests for IsoscelesTriangle + */ + @Test + public void testIsoscelesTriangle() { + // TODO: test IsoscelesTriangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MammalAnyofTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MammalAnyofTest.java new file mode 100644 index 000000000000..6eb811f21cd6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MammalAnyofTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for MammalAnyof + */ +public class MammalAnyofTest { + private final MammalAnyof model = new MammalAnyof(); + + /** + * Model tests for MammalAnyof + */ + @Test + public void testMammalAnyof() { + // TODO: test MammalAnyof + } + + /** + * Test the property 'hasBaleen' + */ + @Test + public void hasBaleenTest() { + // TODO: test hasBaleen + } + + /** + * Test the property 'hasTeeth' + */ + @Test + public void hasTeethTest() { + // TODO: test hasTeeth + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MammalTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MammalTest.java new file mode 100644 index 000000000000..3995c274e448 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MammalTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Mammal + */ +public class MammalTest { + private final Mammal model = new Mammal(); + + /** + * Model tests for Mammal + */ + @Test + public void testMammal() { + // TODO: test Mammal + } + + /** + * Test the property 'hasBaleen' + */ + @Test + public void hasBaleenTest() { + // TODO: test hasBaleen + } + + /** + * Test the property 'hasTeeth' + */ + @Test + public void hasTeethTest() { + // TODO: test hasTeeth + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MapTestTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MapTestTest.java new file mode 100644 index 000000000000..62b050c11460 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MapTestTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for MapTest + */ +public class MapTestTest { + private final MapTest model = new MapTest(); + + /** + * Model tests for MapTest + */ + @Test + public void testMapTest() { + // TODO: test MapTest + } + + /** + * Test the property 'mapMapOfString' + */ + @Test + public void mapMapOfStringTest() { + // TODO: test mapMapOfString + } + + /** + * Test the property 'mapOfEnumString' + */ + @Test + public void mapOfEnumStringTest() { + // TODO: test mapOfEnumString + } + + /** + * Test the property 'directMap' + */ + @Test + public void directMapTest() { + // TODO: test directMap + } + + /** + * Test the property 'indirectMap' + */ + @Test + public void indirectMapTest() { + // TODO: test indirectMap + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java new file mode 100644 index 000000000000..16644aa3e7c9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ +public class MixedPropertiesAndAdditionalPropertiesClassTest { + private final MixedPropertiesAndAdditionalPropertiesClass model = new MixedPropertiesAndAdditionalPropertiesClass(); + + /** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ + @Test + public void testMixedPropertiesAndAdditionalPropertiesClass() { + // TODO: test MixedPropertiesAndAdditionalPropertiesClass + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'map' + */ + @Test + public void mapTest() { + // TODO: test map + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/Model200ResponseTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/Model200ResponseTest.java new file mode 100644 index 000000000000..14c62bbeb304 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/Model200ResponseTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Model200Response + */ +public class Model200ResponseTest { + private final Model200Response model = new Model200Response(); + + /** + * Model tests for Model200Response + */ + @Test + public void testModel200Response() { + // TODO: test Model200Response + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java new file mode 100644 index 000000000000..7428be140174 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelFileTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelFileTest.java new file mode 100644 index 000000000000..4aebe8858b01 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelFileTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ModelFile + */ +public class ModelFileTest { + private final ModelFile model = new ModelFile(); + + /** + * Model tests for ModelFile + */ + @Test + public void testModelFile() { + // TODO: test ModelFile + } + + /** + * Test the property 'sourceURI' + */ + @Test + public void sourceURITest() { + // TODO: test sourceURI + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelListTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelListTest.java new file mode 100644 index 000000000000..ee47f2e401a9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelListTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ModelList + */ +public class ModelListTest { + private final ModelList model = new ModelList(); + + /** + * Model tests for ModelList + */ + @Test + public void testModelList() { + // TODO: test ModelList + } + + /** + * Test the property '_123list' + */ + @Test + public void _123listTest() { + // TODO: test _123list + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelReturnTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelReturnTest.java new file mode 100644 index 000000000000..6cee4f231d50 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelReturnTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ModelReturn + */ +public class ModelReturnTest { + private final ModelReturn model = new ModelReturn(); + + /** + * Model tests for ModelReturn + */ + @Test + public void testModelReturn() { + // TODO: test ModelReturn + } + + /** + * Test the property '_return' + */ + @Test + public void _returnTest() { + // TODO: test _return + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelWithOneOfAnyOfPropertiesTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelWithOneOfAnyOfPropertiesTest.java new file mode 100644 index 000000000000..0f5df47d54e9 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ModelWithOneOfAnyOfPropertiesTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ModelWithOneOfAnyOfProperties + */ +public class ModelWithOneOfAnyOfPropertiesTest { + private final ModelWithOneOfAnyOfProperties model = new ModelWithOneOfAnyOfProperties(); + + /** + * Model tests for ModelWithOneOfAnyOfProperties + */ + @Test + public void testModelWithOneOfAnyOfProperties() { + // TODO: test ModelWithOneOfAnyOfProperties + } + + /** + * Test the property 'oneofProp' + */ + @Test + public void oneofPropTest() { + // TODO: test oneofProp + } + + /** + * Test the property 'anyofProp' + */ + @Test + public void anyofPropTest() { + // TODO: test anyofProp + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NameTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NameTest.java new file mode 100644 index 000000000000..63847de9baa6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NameTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Name + */ +public class NameTest { + private final Name model = new Name(); + + /** + * Model tests for Name + */ + @Test + public void testName() { + // TODO: test Name + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'snakeCase' + */ + @Test + public void snakeCaseTest() { + // TODO: test snakeCase + } + + /** + * Test the property 'property' + */ + @Test + public void propertyTest() { + // TODO: test property + } + + /** + * Test the property '_123number' + */ + @Test + public void _123numberTest() { + // TODO: test _123number + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NestedArrayWithDefaultValuesTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NestedArrayWithDefaultValuesTest.java new file mode 100644 index 000000000000..3478dbc48db6 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NestedArrayWithDefaultValuesTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NestedArrayWithDefaultValues + */ +public class NestedArrayWithDefaultValuesTest { + private final NestedArrayWithDefaultValues model = new NestedArrayWithDefaultValues(); + + /** + * Model tests for NestedArrayWithDefaultValues + */ + @Test + public void testNestedArrayWithDefaultValues() { + // TODO: test NestedArrayWithDefaultValues + } + + /** + * Test the property 'nestedArray' + */ + @Test + public void nestedArrayTest() { + // TODO: test nestedArray + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTagTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTagTest.java new file mode 100644 index 000000000000..25cd4fe4c0cc --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTagTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NewPetCategoryInlineAllofAllOfCategoryTag + */ +public class NewPetCategoryInlineAllofAllOfCategoryTagTest { + private final NewPetCategoryInlineAllofAllOfCategoryTag model = new NewPetCategoryInlineAllofAllOfCategoryTag(); + + /** + * Model tests for NewPetCategoryInlineAllofAllOfCategoryTag + */ + @Test + public void testNewPetCategoryInlineAllofAllOfCategoryTag() { + // TODO: test NewPetCategoryInlineAllofAllOfCategoryTag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetCategoryInlineAllofTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetCategoryInlineAllofTest.java new file mode 100644 index 000000000000..cf903ef0ed30 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetCategoryInlineAllofTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NewPetCategoryInlineAllof + */ +public class NewPetCategoryInlineAllofTest { + private final NewPetCategoryInlineAllof model = new NewPetCategoryInlineAllof(); + + /** + * Model tests for NewPetCategoryInlineAllof + */ + @Test + public void testNewPetCategoryInlineAllof() { + // TODO: test NewPetCategoryInlineAllof + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'categoryTag' + */ + @Test + public void categoryTagTest() { + // TODO: test categoryTag + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetTest.java new file mode 100644 index 000000000000..abf95980baee --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NewPetTest.java @@ -0,0 +1,105 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NewPet + */ +public class NewPetTest { + private final NewPet model = new NewPet(); + + /** + * Model tests for NewPet + */ + @Test + public void testNewPet() { + // TODO: test NewPet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'categoryInlineAllof' + */ + @Test + public void categoryInlineAllofTest() { + // TODO: test categoryInlineAllof + } + + /** + * Test the property 'categoryAllOfRef' + */ + @Test + public void categoryAllOfRefTest() { + // TODO: test categoryAllOfRef + } + + /** + * Test the property 'categoryAllOfRefDescription' + */ + @Test + public void categoryAllOfRefDescriptionTest() { + // TODO: test categoryAllOfRefDescription + } + + /** + * Test the property 'categoryAllOfRefDescriptionReadonly' + */ + @Test + public void categoryAllOfRefDescriptionReadonlyTest() { + // TODO: test categoryAllOfRefDescriptionReadonly + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableClassTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableClassTest.java new file mode 100644 index 000000000000..c069166c672e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableClassTest.java @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NullableClass + */ +public class NullableClassTest { + private final NullableClass model = new NullableClass(); + + /** + * Model tests for NullableClass + */ + @Test + public void testNullableClass() { + // TODO: test NullableClass + } + + /** + * Test the property 'integerProp' + */ + @Test + public void integerPropTest() { + // TODO: test integerProp + } + + /** + * Test the property 'numberProp' + */ + @Test + public void numberPropTest() { + // TODO: test numberProp + } + + /** + * Test the property 'booleanProp' + */ + @Test + public void booleanPropTest() { + // TODO: test booleanProp + } + + /** + * Test the property 'stringProp' + */ + @Test + public void stringPropTest() { + // TODO: test stringProp + } + + /** + * Test the property 'dateProp' + */ + @Test + public void datePropTest() { + // TODO: test dateProp + } + + /** + * Test the property 'datetimeProp' + */ + @Test + public void datetimePropTest() { + // TODO: test datetimeProp + } + + /** + * Test the property 'arrayNullableProp' + */ + @Test + public void arrayNullablePropTest() { + // TODO: test arrayNullableProp + } + + /** + * Test the property 'arrayAndItemsNullableProp' + */ + @Test + public void arrayAndItemsNullablePropTest() { + // TODO: test arrayAndItemsNullableProp + } + + /** + * Test the property 'arrayItemsNullable' + */ + @Test + public void arrayItemsNullableTest() { + // TODO: test arrayItemsNullable + } + + /** + * Test the property 'objectNullableProp' + */ + @Test + public void objectNullablePropTest() { + // TODO: test objectNullableProp + } + + /** + * Test the property 'objectAndItemsNullableProp' + */ + @Test + public void objectAndItemsNullablePropTest() { + // TODO: test objectAndItemsNullableProp + } + + /** + * Test the property 'objectItemsNullable' + */ + @Test + public void objectItemsNullableTest() { + // TODO: test objectItemsNullable + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableEnumTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableEnumTest.java new file mode 100644 index 000000000000..13f44d4a4e2c --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableEnumTest.java @@ -0,0 +1,31 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NullableEnum + */ +public class NullableEnumTest { + /** + * Model tests for NullableEnum + */ + @Test + public void testNullableEnum() { + // TODO: test NullableEnum + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapErrorTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapErrorTest.java new file mode 100644 index 000000000000..f8632dca7840 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapErrorTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NullableFieldsMapError + */ +public class NullableFieldsMapErrorTest { + private final NullableFieldsMapError model = new NullableFieldsMapError(); + + /** + * Model tests for NullableFieldsMapError + */ + @Test + public void testNullableFieldsMapError() { + // TODO: test NullableFieldsMapError + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'reason' + */ + @Test + public void reasonTest() { + // TODO: test reason + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapResponseTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapResponseTest.java new file mode 100644 index 000000000000..2edf12aea6e5 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapResponseTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NullableFieldsMapResponse + */ +public class NullableFieldsMapResponseTest { + private final NullableFieldsMapResponse model = new NullableFieldsMapResponse(); + + /** + * Model tests for NullableFieldsMapResponse + */ + @Test + public void testNullableFieldsMapResponse() { + // TODO: test NullableFieldsMapResponse + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'positions' + */ + @Test + public void positionsTest() { + // TODO: test positions + } + + /** + * Test the property 'reason' + */ + @Test + public void reasonTest() { + // TODO: test reason + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapSuccessTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapSuccessTest.java new file mode 100644 index 000000000000..9494e3821ed0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsMapSuccessTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NullableFieldsMapSuccess + */ +public class NullableFieldsMapSuccessTest { + private final NullableFieldsMapSuccess model = new NullableFieldsMapSuccess(); + + /** + * Model tests for NullableFieldsMapSuccess + */ + @Test + public void testNullableFieldsMapSuccess() { + // TODO: test NullableFieldsMapSuccess + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'positions' + */ + @Test + public void positionsTest() { + // TODO: test positions + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsValueTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsValueTest.java new file mode 100644 index 000000000000..7a2ad9a1cd9b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableFieldsValueTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NullableFieldsValue + */ +public class NullableFieldsValueTest { + private final NullableFieldsValue model = new NullableFieldsValue(); + + /** + * Model tests for NullableFieldsValue + */ + @Test + public void testNullableFieldsValue() { + // TODO: test NullableFieldsValue + } + + /** + * Test the property 'before' + */ + @Test + public void beforeTest() { + // TODO: test before + } + + /** + * Test the property 'after' + */ + @Test + public void afterTest() { + // TODO: test after + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableShapeTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableShapeTest.java new file mode 100644 index 000000000000..fddb95c3fce0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NullableShapeTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NullableShape + */ +public class NullableShapeTest { + private final NullableShape model = new NullableShape(); + + /** + * Model tests for NullableShape + */ + @Test + public void testNullableShape() { + // TODO: test NullableShape + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NumberOnlyTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NumberOnlyTest.java new file mode 100644 index 000000000000..5f927587ca6d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/NumberOnlyTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for NumberOnly + */ +public class NumberOnlyTest { + private final NumberOnly model = new NumberOnly(); + + /** + * Model tests for NumberOnly + */ + @Test + public void testNumberOnly() { + // TODO: test NumberOnly + } + + /** + * Test the property 'justNumber' + */ + @Test + public void justNumberTest() { + // TODO: test justNumber + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java new file mode 100644 index 000000000000..4df527648eb5 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ObjectWithDeprecatedFields + */ +public class ObjectWithDeprecatedFieldsTest { + private final ObjectWithDeprecatedFields model = new ObjectWithDeprecatedFields(); + + /** + * Model tests for ObjectWithDeprecatedFields + */ + @Test + public void testObjectWithDeprecatedFields() { + // TODO: test ObjectWithDeprecatedFields + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'deprecatedRef' + */ + @Test + public void deprecatedRefTest() { + // TODO: test deprecatedRef + } + + /** + * Test the property 'bars' + */ + @Test + public void barsTest() { + // TODO: test bars + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OrderTest.java new file mode 100644 index 000000000000..ce5b41727fa0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OrderTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterCompositeTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterCompositeTest.java new file mode 100644 index 000000000000..f1e55d713d3f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterCompositeTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for OuterComposite + */ +public class OuterCompositeTest { + private final OuterComposite model = new OuterComposite(); + + /** + * Model tests for OuterComposite + */ + @Test + public void testOuterComposite() { + // TODO: test OuterComposite + } + + /** + * Test the property 'myNumber' + */ + @Test + public void myNumberTest() { + // TODO: test myNumber + } + + /** + * Test the property 'myString' + */ + @Test + public void myStringTest() { + // TODO: test myString + } + + /** + * Test the property 'myBoolean' + */ + @Test + public void myBooleanTest() { + // TODO: test myBoolean + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java new file mode 100644 index 000000000000..26eb0d06704e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java @@ -0,0 +1,31 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for OuterEnumDefaultValue + */ +public class OuterEnumDefaultValueTest { + /** + * Model tests for OuterEnumDefaultValue + */ + @Test + public void testOuterEnumDefaultValue() { + // TODO: test OuterEnumDefaultValue + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java new file mode 100644 index 000000000000..27eb226577fa --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java @@ -0,0 +1,31 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for OuterEnumIntegerDefaultValue + */ +public class OuterEnumIntegerDefaultValueTest { + /** + * Model tests for OuterEnumIntegerDefaultValue + */ + @Test + public void testOuterEnumIntegerDefaultValue() { + // TODO: test OuterEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java new file mode 100644 index 000000000000..fe8515c7b371 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java @@ -0,0 +1,31 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for OuterEnumInteger + */ +public class OuterEnumIntegerTest { + /** + * Model tests for OuterEnumInteger + */ + @Test + public void testOuterEnumInteger() { + // TODO: test OuterEnumInteger + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumTest.java new file mode 100644 index 000000000000..3c94c00a1137 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/OuterEnumTest.java @@ -0,0 +1,31 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for OuterEnum + */ +public class OuterEnumTest { + /** + * Model tests for OuterEnum + */ + @Test + public void testOuterEnum() { + // TODO: test OuterEnum + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ParentPetTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ParentPetTest.java new file mode 100644 index 000000000000..4a29971d9dde --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ParentPetTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ParentPet + */ +public class ParentPetTest { + private final ParentPet model = new ParentPet(); + + /** + * Model tests for ParentPet + */ + @Test + public void testParentPet() { + // TODO: test ParentPet + } + + /** + * Test the property 'petType' + */ + @Test + public void petTypeTest() { + // TODO: test petType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetCompositionTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetCompositionTest.java new file mode 100644 index 000000000000..6c4ad580173a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetCompositionTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for PetComposition + */ +public class PetCompositionTest { + private final PetComposition model = new PetComposition(); + + /** + * Model tests for PetComposition + */ + @Test + public void testPetComposition() { + // TODO: test PetComposition + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetRefTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetRefTest.java new file mode 100644 index 000000000000..e9a98429e860 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetRefTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for PetRef + */ +public class PetRefTest { + private final PetRef model = new PetRef(); + + /** + * Model tests for PetRef + */ + @Test + public void testPetRef() { + // TODO: test PetRef + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 000000000000..cdadf92e9d32 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetUsingAllOfTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetUsingAllOfTest.java new file mode 100644 index 000000000000..29b0b4281ced --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetUsingAllOfTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for PetUsingAllOf + */ +public class PetUsingAllOfTest { + private final PetUsingAllOf model = new PetUsingAllOf(); + + /** + * Model tests for PetUsingAllOf + */ + @Test + public void testPetUsingAllOf() { + // TODO: test PetUsingAllOf + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetWithRequiredTagsTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetWithRequiredTagsTest.java new file mode 100644 index 000000000000..ad603dd55137 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PetWithRequiredTagsTest.java @@ -0,0 +1,81 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for PetWithRequiredTags + */ +public class PetWithRequiredTagsTest { + private final PetWithRequiredTags model = new PetWithRequiredTags(); + + /** + * Model tests for PetWithRequiredTags + */ + @Test + public void testPetWithRequiredTags() { + // TODO: test PetWithRequiredTags + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PigTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PigTest.java new file mode 100644 index 000000000000..ced21c503e39 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PigTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Pig + */ +public class PigTest { + private final Pig model = new Pig(); + + /** + * Model tests for Pig + */ + @Test + public void testPig() { + // TODO: test Pig + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PropertyNameCollisionTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PropertyNameCollisionTest.java new file mode 100644 index 000000000000..348ab395230d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/PropertyNameCollisionTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for PropertyNameCollision + */ +public class PropertyNameCollisionTest { + private final PropertyNameCollision model = new PropertyNameCollision(); + + /** + * Model tests for PropertyNameCollision + */ + @Test + public void testPropertyNameCollision() { + // TODO: test PropertyNameCollision + } + + /** + * Test the property 'underscoreType' + */ + @Test + public void underscoreTypeTest() { + // TODO: test underscoreType + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'typeWithUnderscore' + */ + @Test + public void typeWithUnderscoreTest() { + // TODO: test typeWithUnderscore + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java new file mode 100644 index 000000000000..9034c58f4798 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for QuadrilateralInterface + */ +public class QuadrilateralInterfaceTest { + private final QuadrilateralInterface model = new QuadrilateralInterface(); + + /** + * Model tests for QuadrilateralInterface + */ + @Test + public void testQuadrilateralInterface() { + // TODO: test QuadrilateralInterface + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/QuadrilateralTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/QuadrilateralTest.java new file mode 100644 index 000000000000..e02710741891 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/QuadrilateralTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Quadrilateral + */ +public class QuadrilateralTest { + private final Quadrilateral model = new Quadrilateral(); + + /** + * Model tests for Quadrilateral + */ + @Test + public void testQuadrilateral() { + // TODO: test Quadrilateral + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java new file mode 100644 index 000000000000..c7c8e234d555 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ReadOnlyFirst + */ +public class ReadOnlyFirstTest { + private final ReadOnlyFirst model = new ReadOnlyFirst(); + + /** + * Model tests for ReadOnlyFirst + */ + @Test + public void testReadOnlyFirst() { + // TODO: test ReadOnlyFirst + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'baz' + */ + @Test + public void bazTest() { + // TODO: test baz + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/RequiredNullableBodyTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/RequiredNullableBodyTest.java new file mode 100644 index 000000000000..3eaf3e0565b0 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/RequiredNullableBodyTest.java @@ -0,0 +1,145 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for RequiredNullableBody + */ +public class RequiredNullableBodyTest { + private final RequiredNullableBody model = new RequiredNullableBody(); + + /** + * Model tests for RequiredNullableBody + */ + @Test + public void testRequiredNullableBody() { + // TODO: test RequiredNullableBody + } + + /** + * Test the property 'integerProp' + */ + @Test + public void integerPropTest() { + // TODO: test integerProp + } + + /** + * Test the property 'numberProp' + */ + @Test + public void numberPropTest() { + // TODO: test numberProp + } + + /** + * Test the property 'booleanProp' + */ + @Test + public void booleanPropTest() { + // TODO: test booleanProp + } + + /** + * Test the property 'stringProp' + */ + @Test + public void stringPropTest() { + // TODO: test stringProp + } + + /** + * Test the property 'dateProp' + */ + @Test + public void datePropTest() { + // TODO: test dateProp + } + + /** + * Test the property 'datetimeProp' + */ + @Test + public void datetimePropTest() { + // TODO: test datetimeProp + } + + /** + * Test the property 'arrayNullableProp' + */ + @Test + public void arrayNullablePropTest() { + // TODO: test arrayNullableProp + } + + /** + * Test the property 'arrayAndItemsNullableProp' + */ + @Test + public void arrayAndItemsNullablePropTest() { + // TODO: test arrayAndItemsNullableProp + } + + /** + * Test the property 'arrayItemsNullable' + */ + @Test + public void arrayItemsNullableTest() { + // TODO: test arrayItemsNullable + } + + /** + * Test the property 'objectNullableProp' + */ + @Test + public void objectNullablePropTest() { + // TODO: test objectNullableProp + } + + /** + * Test the property 'objectAndItemsNullableProp' + */ + @Test + public void objectAndItemsNullablePropTest() { + // TODO: test objectAndItemsNullableProp + } + + /** + * Test the property 'objectItemsNullable' + */ + @Test + public void objectItemsNullableTest() { + // TODO: test objectItemsNullable + } + + /** + * Test the property 'customRefEnum' + */ + @Test + public void customRefEnumTest() { + // TODO: test customRefEnum + } + + /** + * Test the property 'customEnum' + */ + @Test + public void customEnumTest() { + // TODO: test customEnum + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScalarAnyOfTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScalarAnyOfTest.java new file mode 100644 index 000000000000..0cf202d314ad --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScalarAnyOfTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ScalarAnyOf + */ +public class ScalarAnyOfTest { + private final ScalarAnyOf model = new ScalarAnyOf(); + + /** + * Model tests for ScalarAnyOf + */ + @Test + public void testScalarAnyOf() { + // TODO: test ScalarAnyOf + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScalarTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScalarTest.java new file mode 100644 index 000000000000..9f1b5506866a --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScalarTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Scalar + */ +public class ScalarTest { + private final Scalar model = new Scalar(); + + /** + * Model tests for Scalar + */ + @Test + public void testScalar() { + // TODO: test Scalar + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java new file mode 100644 index 000000000000..e2115594a251 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ScaleneTriangle + */ +public class ScaleneTriangleTest { + private final ScaleneTriangle model = new ScaleneTriangle(); + + /** + * Model tests for ScaleneTriangle + */ + @Test + public void testScaleneTriangle() { + // TODO: test ScaleneTriangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java new file mode 100644 index 000000000000..a9d3df83e132 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ShapeInterface + */ +public class ShapeInterfaceTest { + private final ShapeInterface model = new ShapeInterface(); + + /** + * Model tests for ShapeInterface + */ + @Test + public void testShapeInterface() { + // TODO: test ShapeInterface + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java new file mode 100644 index 000000000000..43d3b8b25790 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for ShapeOrNull + */ +public class ShapeOrNullTest { + private final ShapeOrNull model = new ShapeOrNull(); + + /** + * Model tests for ShapeOrNull + */ + @Test + public void testShapeOrNull() { + // TODO: test ShapeOrNull + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeTest.java new file mode 100644 index 000000000000..3614747257d1 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ShapeTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Shape + */ +public class ShapeTest { + private final Shape model = new Shape(); + + /** + * Model tests for Shape + */ + @Test + public void testShape() { + // TODO: test Shape + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java new file mode 100644 index 000000000000..223afb32c9bc --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for SimpleQuadrilateral + */ +public class SimpleQuadrilateralTest { + private final SimpleQuadrilateral model = new SimpleQuadrilateral(); + + /** + * Model tests for SimpleQuadrilateral + */ + @Test + public void testSimpleQuadrilateral() { + // TODO: test SimpleQuadrilateral + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java new file mode 100644 index 000000000000..fd11c3ea318b --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for SpecialModelName + */ +public class SpecialModelNameTest { + private final SpecialModelName model = new SpecialModelName(); + + /** + * Model tests for SpecialModelName + */ + @Test + public void testSpecialModelName() { + // TODO: test SpecialModelName + } + + /** + * Test the property '$specialPropertyName' + */ + @Test + public void $specialPropertyNameTest() { + // TODO: test $specialPropertyName + } + + /** + * Test the property 'specialModelName' + */ + @Test + public void specialModelNameTest() { + // TODO: test specialModelName + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 000000000000..627f8916f4cc --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequestTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequestTest.java new file mode 100644 index 000000000000..24fdcce3b572 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequestTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for TestInlineFreeformAdditionalPropertiesRequest + */ +public class TestInlineFreeformAdditionalPropertiesRequestTest { + private final TestInlineFreeformAdditionalPropertiesRequest model = new TestInlineFreeformAdditionalPropertiesRequest(); + + /** + * Model tests for TestInlineFreeformAdditionalPropertiesRequest + */ + @Test + public void testTestInlineFreeformAdditionalPropertiesRequest() { + // TODO: test TestInlineFreeformAdditionalPropertiesRequest + } + + /** + * Test the property 'someProperty' + */ + @Test + public void somePropertyTest() { + // TODO: test someProperty + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java new file mode 100644 index 000000000000..084eaa2729ec --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for TriangleInterface + */ +public class TriangleInterfaceTest { + private final TriangleInterface model = new TriangleInterface(); + + /** + * Model tests for TriangleInterface + */ + @Test + public void testTriangleInterface() { + // TODO: test TriangleInterface + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TriangleTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TriangleTest.java new file mode 100644 index 000000000000..07b8e6b4d3d5 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/TriangleTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Triangle + */ +public class TriangleTest { + private final Triangle model = new Triangle(); + + /** + * Model tests for Triangle + */ + @Test + public void testTriangle() { + // TODO: test Triangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/UserTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/UserTest.java new file mode 100644 index 000000000000..c6317e70073e --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/UserTest.java @@ -0,0 +1,129 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + + /** + * Test the property 'objectWithNoDeclaredProps' + */ + @Test + public void objectWithNoDeclaredPropsTest() { + // TODO: test objectWithNoDeclaredProps + } + + /** + * Test the property 'objectWithNoDeclaredPropsNullable' + */ + @Test + public void objectWithNoDeclaredPropsNullableTest() { + // TODO: test objectWithNoDeclaredPropsNullable + } + + /** + * Test the property 'anyTypeProp' + */ + @Test + public void anyTypePropTest() { + // TODO: test anyTypeProp + } + + /** + * Test the property 'anyTypePropNullable' + */ + @Test + public void anyTypePropNullableTest() { + // TODO: test anyTypePropNullable + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ValueTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ValueTest.java new file mode 100644 index 000000000000..581fa58e5c04 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ValueTest.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Value + */ +public class ValueTest { + private final Value model = new Value(); + + /** + * Model tests for Value + */ + @Test + public void testValue() { + // TODO: test Value + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/VariableTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/VariableTest.java new file mode 100644 index 000000000000..fa809e9e5555 --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/VariableTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Variable + */ +public class VariableTest { + private final Variable model = new Variable(); + + /** + * Model tests for Variable + */ + @Test + public void testVariable() { + // TODO: test Variable + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'value' + */ + @Test + public void valueTest() { + // TODO: test value + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/WhaleTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/WhaleTest.java new file mode 100644 index 000000000000..2b62f2859a7f --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/WhaleTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Whale + */ +public class WhaleTest { + private final Whale model = new Whale(); + + /** + * Model tests for Whale + */ + @Test + public void testWhale() { + // TODO: test Whale + } + + /** + * Test the property 'hasBaleen' + */ + @Test + public void hasBaleenTest() { + // TODO: test hasBaleen + } + + /** + * Test the property 'hasTeeth' + */ + @Test + public void hasTeethTest() { + // TODO: test hasTeeth + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ZebraTest.java b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ZebraTest.java new file mode 100644 index 000000000000..348d3e406d3d --- /dev/null +++ b/samples/client/petstore/java/okhttp/src/test/java/org/openapitools/client/model/ZebraTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for Zebra + */ +public class ZebraTest { + private final Zebra model = new Zebra(); + + /** + * Model tests for Zebra + */ + @Test + public void testZebra() { + // TODO: test Zebra + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +}