diff --git a/bin/utils/test_file_list.yaml b/bin/utils/test_file_list.yaml index 538362b25d36..e24d8f486edc 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: b1b1d31e0df17f0b68cf2747a4a53879f12acb1bf2860e45385c679c1efe9894 + sha256: 074f090e5df50448f3309af83ce30690cd50c83d3675e555de7d359f42d26020 - 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 08fe95493a6a..9961208a32bf 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 @@ -434,6 +434,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens } {{/isString}} {{#isModel}} + {{^isEnum}} {{#required}} {{#isNullable}} if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { @@ -450,6 +451,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); } {{/required}} + {{/isEnum}} {{/isModel}} {{#isEnum}} {{#required}} 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 bde436fcabcb..46b1c7d55052 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 @@ -961,6 +961,20 @@ paths: - type: array items: type: integer + /fake/nullable-required-fields-anyof: + get: + tags: + - fake + summary: test anyOf with map of objects containing nullable required fields + description: 'Tests that anyOf deserialization works when object values contain required fields that are nullable (e.g. Record)' + operationId: testNullableRequiredFieldsAnyOf + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/NullableFieldsMapResponse' /fake/anyOfWIthSameErasure: get: description: Test route, this shouldn't cause a compiler error @@ -2866,3 +2880,46 @@ components: allOf: - $ref: '#/components/schemas/Height' default: 32.1 + NullableFieldsValue: + description: "Object with required but nullable string fields" + type: object + properties: + before: + type: string + nullable: true + after: + type: string + nullable: true + required: + - before + - after + NullableFieldsMapSuccess: + description: "Success response containing a map of objects with nullable fields" + type: object + additionalProperties: false + properties: + status: + type: string + positions: + type: object + additionalProperties: + $ref: '#/components/schemas/NullableFieldsValue' + required: + - status + - positions + NullableFieldsMapError: + description: "Error response" + type: object + additionalProperties: false + properties: + status: + type: string + reason: + type: string + required: + - status + - reason + NullableFieldsMapResponse: + anyOf: + - $ref: '#/components/schemas/NullableFieldsMapSuccess' + - $ref: '#/components/schemas/NullableFieldsMapError' diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES index c64d152e6706..9538aa66cce5 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES @@ -80,6 +80,10 @@ 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 @@ -231,6 +235,10 @@ 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 diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index 78482d179dc0..5f2c66fecc3e 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -142,6 +142,7 @@ Class | Method | HTTP request | Description *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 @@ -242,6 +243,10 @@ Class | Method | HTTP request | Description - [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) diff --git a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml index ef5aa7ad125b..eb420a850cb9 100644 --- a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml @@ -1021,6 +1021,24 @@ paths: 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" @@ -2998,6 +3016,58 @@ components: - $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: + positions: + key: + before: before + after: after + status: status + 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: diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index 4a9b877cd205..00d888ebe6e8 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -25,6 +25,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**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 | @@ -1380,6 +1381,64 @@ No authorization required |-------------|-------------|------------------| | **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.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 { + 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) diff --git a/samples/client/petstore/java/okhttp-gson/docs/NullableFieldsMapError.md b/samples/client/petstore/java/okhttp-gson/docs/NullableFieldsMapError.md new file mode 100644 index 000000000000..c129f355904a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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-gson/docs/NullableFieldsMapResponse.md b/samples/client/petstore/java/okhttp-gson/docs/NullableFieldsMapResponse.md new file mode 100644 index 000000000000..de7b03be5807 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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-gson/docs/NullableFieldsMapSuccess.md b/samples/client/petstore/java/okhttp-gson/docs/NullableFieldsMapSuccess.md new file mode 100644 index 000000000000..0ce60cd148f9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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-gson/docs/NullableFieldsValue.md b/samples/client/petstore/java/okhttp-gson/docs/NullableFieldsValue.md new file mode 100644 index 000000000000..397f73f74007 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/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-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 98b9c070691b..7062e2f15e41 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 @@ -311,6 +311,10 @@ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, Stri gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPetCategoryInlineAllof.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NewPetCategoryInlineAllofAllOfCategoryTag.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableClass.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsMapError.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsMapResponse.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsMapSuccess.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableFieldsValue.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NullableShape.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.NumberOnly.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ObjectWithDeprecatedFields.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 eea2b5f01fce..34a42b434db7 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 @@ -36,6 +36,7 @@ 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; @@ -3014,6 +3015,123 @@ public okhttp3.Call testJsonFormDataAsync(@javax.annotation.Nonnull String param 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) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapError.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapError.java new file mode 100644 index 000000000000..c11cf0087e5f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapError.java @@ -0,0 +1,238 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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 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; + +/** + * Error response + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.23.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())); + } + } + + 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-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapResponse.java new file mode 100644 index 000000000000..28a2ecb975f6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapResponse.java @@ -0,0 +1,270 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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.Map; +import org.openapitools.client.model.NullableFieldsMapError; +import org.openapitools.client.model.NullableFieldsMapSuccess; +import org.openapitools.client.model.NullableFieldsValue; + + + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +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 com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.23.0-SNAPSHOT") +public class NullableFieldsMapResponse extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(NullableFieldsMapResponse.class.getName()); + + 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; + } + + // check if the actual instance is of the type `NullableFieldsMapSuccess` + if (value.getActualInstance() instanceof NullableFieldsMapSuccess) { + JsonElement element = adapterNullableFieldsMapSuccess.toJsonTree((NullableFieldsMapSuccess)value.getActualInstance()); + elementAdapter.write(out, element); + return; + } + // check if the actual instance is of the type `NullableFieldsMapError` + if (value.getActualInstance() instanceof NullableFieldsMapError) { + JsonElement element = adapterNullableFieldsMapError.toJsonTree((NullableFieldsMapError)value.getActualInstance()); + elementAdapter.write(out, element); + return; + } + throw new IOException("Failed to serialize as the type doesn't match anyOf schemas: NullableFieldsMapError, NullableFieldsMapSuccess"); + } + + @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); + actualAdapter = adapterNullableFieldsMapSuccess; + NullableFieldsMapResponse ret = new NullableFieldsMapResponse(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format(java.util.Locale.ROOT, "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); + actualAdapter = adapterNullableFieldsMapError; + NullableFieldsMapResponse ret = new NullableFieldsMapResponse(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format(java.util.Locale.ROOT, "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(java.util.Locale.ROOT, "Failed deserialization for NullableFieldsMapResponse: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); + } + }.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(Object 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. + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof NullableFieldsMapSuccess) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof NullableFieldsMapError) { + 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` + */ + 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` + */ + public NullableFieldsMapError getNullableFieldsMapError() throws ClassCastException { + return (NullableFieldsMapError)super.getActualInstance(); + } + + /** + * 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 { + // validate anyOf schemas one by one + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with NullableFieldsMapSuccess + try { + NullableFieldsMapSuccess.validateJsonElement(jsonElement); + return; + } catch (Exception e) { + errorMessages.add(String.format(java.util.Locale.ROOT, "Deserialization for NullableFieldsMapSuccess failed with `%s`.", e.getMessage())); + // continue to the next one + } + // validate the json string with NullableFieldsMapError + try { + NullableFieldsMapError.validateJsonElement(jsonElement); + return; + } catch (Exception e) { + errorMessages.add(String.format(java.util.Locale.ROOT, "Deserialization for NullableFieldsMapError failed with `%s`.", e.getMessage())); + // continue to the next one + } + throw new IOException(String.format(java.util.Locale.ROOT, "The JSON string is invalid for NullableFieldsMapResponse with anyOf schemas: NullableFieldsMapError, NullableFieldsMapSuccess. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); + } + + /** + * 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-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapSuccess.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapSuccess.java new file mode 100644 index 000000000000..7daf0b64fd7e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsMapSuccess.java @@ -0,0 +1,246 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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.Map; +import org.openapitools.client.model.NullableFieldsValue; + +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; + +/** + * Success response containing a map of objects with nullable fields + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.23.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())); + } + } + + 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-gson/src/main/java/org/openapitools/client/model/NullableFieldsValue.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsValue.java new file mode 100644 index 000000000000..1eee52d63552 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableFieldsValue.java @@ -0,0 +1,319 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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 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; + +/** + * Object with required but nullable string fields + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.23.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())); + } + } + + // 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.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-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 b406db14e130..5b6b2241ce28 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 @@ -39,6 +39,40 @@ public void setup() { 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<>(); diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapErrorTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapErrorTest.java new file mode 100644 index 000000000000..01035f0b3ec8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapErrorTest.java @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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.util.Arrays; +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-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapResponseTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapResponseTest.java new file mode 100644 index 000000000000..7d8cdf3efaed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapResponseTest.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.client.model.NullableFieldsMapError; +import org.openapitools.client.model.NullableFieldsMapSuccess; +import org.openapitools.client.model.NullableFieldsValue; +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-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapSuccessTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapSuccessTest.java new file mode 100644 index 000000000000..48535e633967 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsMapSuccessTest.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.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.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.openapitools.client.model.NullableFieldsValue; +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-gson/src/test/java/org/openapitools/client/model/NullableFieldsValueTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsValueTest.java new file mode 100644 index 000000000000..1bda4317d088 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableFieldsValueTest.java @@ -0,0 +1,56 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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.util.Arrays; +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 + } + +}