diff --git a/bin/utils/test_file_list.yaml b/bin/utils/test_file_list.yaml index 3412fcdca713..5e0ea8a9e346 100644 --- a/bin/utils/test_file_list.yaml +++ b/bin/utils/test_file_list.yaml @@ -10,7 +10,7 @@ - filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ClientTest.java" sha256: 325fdd5d7e2c97790c0fb44f712ab7b2ba022d7e1a5b0056f47b07f342682b6d - filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java" - sha256: 67941355a0a27ed9ff9318b1caa103e78b81b9aff61b594b18be5cd2bb9f6591 + sha256: b1b1d31e0df17f0b68cf2747a4a53879f12acb1bf2860e45385c679c1efe9894 - filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java" sha256: 8b1b8f2a2ad00ccb090873a94a5f73e328b98317d2ec715f53bd7a1accb2a023 - filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetTest.java" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache index 881f2acf72d2..cb19eb603679 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache @@ -385,16 +385,16 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{#isArray}} {{#items.isModel}} {{#required}} - // 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())); + 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())); + } + 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)); + } } - - 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()) { @@ -424,7 +424,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens // 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()) { + } 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}} @@ -438,8 +438,14 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/isString}} {{#isModel}} {{#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}}}` @@ -450,8 +456,14 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/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}}}` @@ -462,8 +474,14 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/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}}}` 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 bb92138888da..94a0a6f4535e 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 @@ -3769,6 +3769,35 @@ public class JavaClientCodegenTest { ); } + @Test + public void testRequiredAndNullableAreBothTrue() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.OKHTTP_GSON) + .setInputSpec("src/test/resources/bugs/issue_18516.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + files.forEach(File::deleteOnExit); + + validateJavaSourceFiles(files); + + Path modelFile = Paths.get(output + "/src/main/java/org/openapitools/client/model/SomeObject.java"); + TestUtils.assertFileContains( + modelFile, + "} else if (!jsonObj.get(\"ids\").isJsonArray() && !jsonObj.get(\"ids\").isJsonNull()) {", + "if (jsonObj.get(\"users\") != null && !jsonObj.get(\"users\").isJsonNull()) {", + "if (!jsonObj.get(\"users\").isJsonArray()) {", + "if (jsonObj.get(\"user\") != null && !jsonObj.get(\"user\").isJsonNull()) {", + "if (jsonObj.get(\"role\") != null && !jsonObj.get(\"role\").isJsonNull()) {", + "if (jsonObj.get(\"custom\") != null && !jsonObj.get(\"custom\").isJsonNull()) {"); + } + @Test(description = "Issue #21051") public void givenComplexObjectHasDefaultValueWhenGenerateThenDefaultAssignmentsAreValid() throws Exception { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); diff --git a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml index 9cf24ac86351..bde436fcabcb 100644 --- a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml @@ -1369,6 +1369,19 @@ paths: $ref: '#/components/schemas/Variable' '400': description: Invalid Value + /fake/required-nullable-body: + get: + tags: + - fake + summary: fields in the response body, required and nullable are both true + description: '' + responses: + '200': + description: success + content: + application/json: + schema: + $ref: '#/components/schemas/RequiredNullableBody' servers: - url: 'http://{server}.swagger.io:{port}/v2' description: petstore server @@ -2768,6 +2781,38 @@ components: $ref: '#/components/schemas/ArrayOneOf' anyof_prop: $ref: '#/components/schemas/ArrayAnyOf' + NullableEnum: + type: string + nullable: true + enum: + - custom + RequiredNullableBody: + allOf: + - $ref: '#/components/schemas/NullableClass' + - type: object + required: + - custom_ref_enum + - custom_enum + - 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 + properties: + custom_ref_enum: + $ref: "#/components/schemas/NullableEnum" + custom_enum: + type: string + nullable: true + enum: + - custom NestedArrayWithDefaultValues: type: object properties: diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_18516.yaml b/modules/openapi-generator/src/test/resources/bugs/issue_18516.yaml new file mode 100644 index 000000000000..fcefeb6b521f --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_18516.yaml @@ -0,0 +1,61 @@ +openapi: 3.0.3 +info: + title: test + description: Test API + version: 1.0.1 + +paths: + /test: + get: + responses: + 200: + description: Valid response + content: + application/json: + schema: + $ref: "#/components/schemas/SomeObject" + +components: + schemas: + SomeObject: + type: object + required: + - ids + - users + - user + - role + - custom + properties: + ids: + type: array + nullable: true + items: + type: integer + users: + type: array + nullable: true + items: + type: object + properties: + id: + type: string + user: + type: object + nullable: true + properties: + id: + type: string + role: + type: string + nullable: true + enum: + - admin + - tenant + custom: + $ref: "#/components/schemas/customEnum" + customEnum: + type: string + nullable: true + enum: + - custom + \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java index 6e11c8a5366b..387783611b19 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java @@ -424,7 +424,7 @@ public class PetWithRequiredNullableCases1 { // 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()) { + } else if (!jsonObj.get("photoUrls").isJsonArray() && !jsonObj.get("photoUrls").isJsonNull()) { 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()) { diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES index 9de4894ad1e8..c64d152e6706 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES @@ -79,6 +79,7 @@ docs/NewPet.md docs/NewPetCategoryInlineAllof.md docs/NewPetCategoryInlineAllofAllOfCategoryTag.md docs/NullableClass.md +docs/NullableEnum.md docs/NullableShape.md docs/NumberOnly.md docs/ObjectWithDeprecatedFields.md @@ -100,6 +101,7 @@ docs/PropertyNameCollision.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredNullableBody.md docs/Scalar.md docs/ScalarAnyOf.md docs/ScaleneTriangle.md @@ -228,6 +230,7 @@ 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/NullableShape.java src/main/java/org/openapitools/client/model/NumberOnly.java src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -248,6 +251,7 @@ 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 diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index 588113b62f87..b39145bd144d 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -127,6 +127,7 @@ Class | Method | HTTP request | Description *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 @@ -240,6 +241,7 @@ Class | Method | HTTP request | Description - [NewPetCategoryInlineAllof](docs/NewPetCategoryInlineAllof.md) - [NewPetCategoryInlineAllofAllOfCategoryTag](docs/NewPetCategoryInlineAllofAllOfCategoryTag.md) - [NullableClass](docs/NullableClass.md) + - [NullableEnum](docs/NullableEnum.md) - [NullableShape](docs/NullableShape.md) - [NumberOnly](docs/NumberOnly.md) - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) @@ -260,6 +262,7 @@ Class | Method | HTTP request | Description - [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) diff --git a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml index 5d897fbe1465..ef5aa7ad125b 100644 --- a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml @@ -1494,6 +1494,21 @@ paths: 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: @@ -2870,6 +2885,62 @@ components: 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: + number_prop: 6.027456183070403 + datetime_prop: 2000-01-23T04:56:07.000+00:00 + custom_ref_enum: custom + boolean_prop: true + string_prop: string_prop + array_nullable_prop: + - "{}" + - "{}" + custom_enum: custom + integer_prop: 0 + array_and_items_nullable_prop: + - "{}" + - "{}" + object_items_nullable: + key: "{}" + object_nullable_prop: + key: "{}" + object_and_items_nullable_prop: + key: "{}" + date_prop: 2000-01-23 + array_items_nullable: + - "{}" + - "{}" NestedArrayWithDefaultValues: properties: nestedArray: diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index eb2f76491a83..4a9b877cd205 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**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 | @@ -395,6 +396,64 @@ No authorization required |-------------|-------------|------------------| | **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.models.*; +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) diff --git a/samples/client/petstore/java/okhttp-gson/docs/NullableEnum.md b/samples/client/petstore/java/okhttp-gson/docs/NullableEnum.md new file mode 100644 index 000000000000..774c8d6b1d70 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/NullableEnum.md @@ -0,0 +1,11 @@ + + +# NullableEnum + +## Enum + + +* `CUSTOM` (value: `"custom"`) + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/RequiredNullableBody.md b/samples/client/petstore/java/okhttp-gson/docs/RequiredNullableBody.md new file mode 100644 index 000000000000..b732ff05be76 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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-gson/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java index 5aaa5ac339df..98b9c070691b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java @@ -327,6 +327,7 @@ public class JSON { gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Quadrilateral.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.QuadrilateralInterface.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ReadOnlyFirst.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.RequiredNullableBody.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Scalar.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ScalarAnyOf.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ScaleneTriangle.CustomTypeAdapterFactory()); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java index 7055253c1a0b..eea2b5f01fce 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -39,6 +39,7 @@ import org.openapitools.client.model.ModelApiResponse; 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; @@ -812,6 +813,123 @@ public class FakeApi { 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) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java index 0039137bb4f3..5fa05e48a089 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java @@ -204,16 +204,16 @@ public class AllOfModelArrayAnyOfAllOfLinkListColumn1 { } } JsonObject jsonObj = jsonElement.getAsJsonObject(); - // ensure the json data is an array - 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())); + 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())); + } + JsonArray jsonArrayvalue = jsonObj.getAsJsonArray("value"); + // validate the required field `value` (array) + for (int i = 0; i < jsonArrayvalue.size(); i++) { + AllOfModelArrayAnyOfAllOfLinkListColumn1Value.validateJsonElement(jsonArrayvalue.get(i)); + } } - - 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 { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableEnum.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableEnum.java new file mode 100644 index 000000000000..d28af0a9d1ea --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java index 041a975c7de0..78182b25bd62 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java @@ -410,16 +410,16 @@ public class PetWithRequiredTags { } 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())); } - // 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())); + 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())); + } + JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags"); + // validate the required field `tags` (array) + for (int i = 0; i < jsonArraytags.size(); i++) { + Tag.validateJsonElement(jsonArraytags.get(i)); + } } - - 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())); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/RequiredNullableBody.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/RequiredNullableBody.java new file mode 100644 index 000000000000..0cd332f2fc81 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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 org.openapitools.client.model.NullableEnum; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openapitools.client.JSON; + +/** + * RequiredNullableBody + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.20.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) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(Arrays.asList("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())); + } + } + + // 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.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-gson/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java index 4552c01cca74..b406db14e130 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java @@ -674,6 +674,15 @@ public class JSONTest { } } + @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)); + assertEquals(json.deserialize(json1, RequiredNullableBody.class), body); + } + @Test public void testDeserializeInputStream() throws Exception { final String str = "\"2016-09-09\""; diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableEnumTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableEnumTest.java new file mode 100644 index 000000000000..8bcd02d221e0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableEnumTest.java @@ -0,0 +1,32 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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 com.google.gson.annotations.SerializedName; +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-gson/src/test/java/org/openapitools/client/model/RequiredNullableBodyTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/RequiredNullableBodyTest.java new file mode 100644 index 000000000000..4adb311eb1ea --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/RequiredNullableBodyTest.java @@ -0,0 +1,160 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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 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 org.openapitools.client.model.NullableEnum; +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 + } + +}