From d4d4c77feeffd12fc76a7a014142843248ce2206 Mon Sep 17 00:00:00 2001 From: Max Date: Sat, 11 May 2024 18:07:02 +0200 Subject: [PATCH] [BUG] [Java] Invalid code generation for oneof types. (#18544) * [BUG] [Java] Invalid code generation for oneof types. #18517 * update samples * [BUG] [Java] Invalid code generation for oneof types. #18517 * [BUG] [Java] Invalid code generation for oneof types. #18517 * [BUG] [Java] Invalid code generation for oneof types. #18544 --- .../okhttp-gson/oneof_model.mustache | 88 ++++- ...points-models-for-testing-okhttp-gson.yaml | 22 ++ .../java/okhttp-gson/.openapi-generator/FILES | 4 + .../petstore/java/okhttp-gson/README.md | 3 + .../java/okhttp-gson/api/openapi.yaml | 29 ++ .../petstore/java/okhttp-gson/docs/FakeApi.md | 59 ++++ .../docs/FreeFormObjectTestClass.md | 14 + .../docs/FreeFormObjectTestClassProperties.md | 12 + .../java/org/openapitools/client/JSON.java | 2 + .../org/openapitools/client/api/FakeApi.java | 114 +++++++ .../client/model/FreeFormObjectTestClass.java | 318 ++++++++++++++++++ .../FreeFormObjectTestClassProperties.java | 282 ++++++++++++++++ .../org/openapitools/client/JSONTest.java | 22 ++ ...FreeFormObjectTestClassPropertiesTest.java | 34 ++ .../model/FreeFormObjectTestClassTest.java | 57 ++++ 15 files changed, 1057 insertions(+), 3 deletions(-) create mode 100644 samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClass.md create mode 100644 samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClassProperties.md create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassPropertiesTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassTest.java diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache index 4a34934dce77..c2cceb5b1fe4 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache @@ -48,15 +48,21 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#oneOf}} {{^isArray}} + {{^isMap}} {{^vendorExtensions.x-duplicated-data-type}} final TypeAdapter<{{{dataType}}}> adapter{{{dataType}}} = gson.getDelegateAdapter(this, TypeToken.get({{{dataType}}}.class)); {{/vendorExtensions.x-duplicated-data-type}} + {{/isMap}} {{/isArray}} {{#isArray}} final Type typeInstance = new TypeToken<{{{dataType}}}>(){}.getType(); final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}} = (TypeAdapter<{{{dataType}}}>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance)); {{/isArray}} + {{#isMap}} + final Type typeInstance = new TypeToken<{{{dataType}}}>(){}.getType(); + final TypeAdapter<{{{dataType}}}> adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}} = (TypeAdapter<{{{dataType}}}>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance)); + {{/isMap}} {{/oneOf}} {{/composedSchemas}} @@ -72,11 +78,18 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#oneOf}} {{^vendorExtensions.x-duplicated-data-type}} // check if the actual instance is of the type `{{{dataType}}}` - if (value.getActualInstance() instanceof {{#isArray}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) { + if (value.getActualInstance() instanceof {{#isArray}}List{{/isArray}}{{#isMap}}Map{{/isMap}}{{^isMap}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isMap}}) { {{#isPrimitiveType}} + {{^isMap}} JsonPrimitive primitive = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonPrimitive(); elementAdapter.write(out, primitive); return; + {{/isMap}} + {{#isMap}} + JsonObject object = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}.toJsonTree(({{{dataType}}})value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, object); + return; + {{/isMap}} {{/isPrimitiveType}} {{^isPrimitiveType}} {{#isArray}} @@ -88,6 +101,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im } {{/isArray}} {{/isPrimitiveType}} + {{^isMap}} {{^isArray}} {{^isPrimitiveType}} JsonElement element = adapter{{{dataType}}}.toJsonTree(({{{dataType}}})value.getActualInstance()); @@ -95,6 +109,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im return; {{/isPrimitiveType}} {{/isArray}} + {{/isMap}} } {{/vendorExtensions.x-duplicated-data-type}} {{/oneOf}} @@ -143,6 +158,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im try { // validate the JSON object to see if any exception is thrown {{^isArray}} + {{^isMap}} {{#isNumber}} if (!jsonElement.getAsJsonPrimitive().isNumber()) { throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); @@ -163,6 +179,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}; {{/isPrimitiveType}} {{/isNumber}} + {{/isMap}} {{/isArray}} {{#isArray}} if (!jsonElement.isJsonArray()) { @@ -194,6 +211,38 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im } actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}; {{/isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + + {{^isFreeFormObject}} + Map map = jsonElement.getAsJsonObject().asMap(); + // validate map items + for(JsonElement element : map.values()) { + {{#items}} + {{#isNumber}} + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isNumber}} + {{^isNumber}} + {{#isPrimitiveType}} + if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isPrimitiveType}} + {{/isNumber}} + {{^isNumber}} + {{^isPrimitiveType}} + {{{dataType}}}.validateJsonElement(element); + {{/isPrimitiveType}} + {{/isNumber}} + {{/items}} + } + {{/isFreeFormObject}} + actualAdapter = adapter{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}; + {{/isMap}} match++; log.log(Level.FINER, "Input data matches schema '{{{dataType}}}'"); } catch (Exception e) { @@ -280,7 +329,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#oneOf}} {{^vendorExtensions.x-duplicated-data-type}} - if (instance instanceof {{#isArray}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) { + if (instance instanceof {{#isArray}}List{{/isArray}}{{#isMap}}Map{{/isMap}}{{^isMap}}{{^isArray}}{{{dataType}}}{{/isArray}}{{/isMap}}) { {{#isArray}} List list = (List) instance; if (list.get(0) instanceof {{{items.dataType}}}) { @@ -322,7 +371,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im * @return The actual instance of `{{{dataType}}}` * @throws ClassCastException if the instance is not `{{{dataType}}}` */ - public {{{dataType}}} get{{#isArray}}{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}() throws ClassCastException { + public {{{dataType}}} get{{#sanitizeGeneric}}{{{dataType}}}{{/sanitizeGeneric}}() throws ClassCastException { return ({{{dataType}}})super.getActualInstance(); } {{/vendorExtensions.x-duplicated-data-type}} @@ -345,6 +394,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im // validate the json string with {{{dataType}}} try { {{^hasVars}} + {{^isMap}} {{^isArray}} {{#isNumber}} if (!jsonElement.getAsJsonPrimitive().isNumber()) { @@ -364,6 +414,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isPrimitiveType}} {{/isNumber}} {{/isArray}} + {{/isMap}} {{#isArray}} if (!jsonElement.isJsonArray()) { throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString())); @@ -392,6 +443,37 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/items}} } {{/isArray}} + {{#isMap}} + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + + {{^isFreeFormObject}} + Map map = jsonElement.getAsJsonObject().asMap(); + // validate map items + for(JsonElement element : map.values()) { + {{#items}} + {{#isNumber}} + if (!jsonElement.getAsJsonPrimitive().isNumber()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isNumber}} + {{^isNumber}} + {{#isPrimitiveType}} + if (!element.getAsJsonPrimitive().is{{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}}()) { + throw new IllegalArgumentException(String.format("Expected array items to be of type {{#isBoolean}}Boolean{{/isBoolean}}{{#isString}}String{{/isString}}{{^isString}}{{^isBoolean}}Number{{/isBoolean}}{{/isString}} in the JSON string but got `%s`", jsonElement.toString())); + } + {{/isPrimitiveType}} + {{/isNumber}} + {{^isNumber}} + {{^isPrimitiveType}} + {{{dataType}}}.validateJsonElement(element); + {{/isPrimitiveType}} + {{/isNumber}} + {{/items}} + } + {{/isFreeFormObject}} + {{/isMap}} {{/hasVars}} {{#hasVars}} {{{.}}}.validateJsonElement(jsonElement); 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 0aff5a7c0957..5e763f1989ab 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 @@ -1048,6 +1048,18 @@ paths: schema: $ref: '#/components/schemas/FileSchemaTestClass' required: true + /fake/get-free-form-object: + get: + tags: + - fake + description: Get a free form object or Json string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObjectTestClass' /fake/test-query-parameters: put: tags: @@ -2035,6 +2047,16 @@ components: type: array items: $ref: '#/components/schemas/File' + FreeFormObjectTestClass: + type: object + properties: + name: + type: string + properties: + oneOf: + - type: string + - type: object + additionalProperties: true File: type: object description: Must be named `File` for test. diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES index 9dd3140d3e43..d42445a12dac 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES @@ -48,6 +48,8 @@ docs/FileSchemaTestClass.md docs/Foo.md docs/FooGetDefaultResponse.md docs/FormatTest.md +docs/FreeFormObjectTestClass.md +docs/FreeFormObjectTestClassProperties.md docs/Fruit.md docs/FruitReq.md docs/GmFruit.md @@ -187,6 +189,8 @@ src/main/java/org/openapitools/client/model/FileSchemaTestClass.java src/main/java/org/openapitools/client/model/Foo.java src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java src/main/java/org/openapitools/client/model/FormatTest.java +src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java +src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java src/main/java/org/openapitools/client/model/Fruit.java src/main/java/org/openapitools/client/model/FruitReq.java src/main/java/org/openapitools/client/model/GmFruit.java diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index d892ad8cf0e5..abd680c94f49 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -119,6 +119,7 @@ Class | Method | HTTP request | Description *AnotherFakeApi* | [**getParameterStringNumber**](docs/AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number *AnotherFakeApi* | [**nullRequestBody**](docs/AnotherFakeApi.md#nullRequestBody) | **GET** /fake/null-request-body | null request body *DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo | +*FakeApi* | [**fakeGetFreeFormObjectGet**](docs/FakeApi.md#fakeGetFreeFormObjectGet) | **GET** /fake/get-free-form-object | *FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | *FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | @@ -205,6 +206,8 @@ Class | Method | HTTP request | Description - [Foo](docs/Foo.md) - [FooGetDefaultResponse](docs/FooGetDefaultResponse.md) - [FormatTest](docs/FormatTest.md) + - [FreeFormObjectTestClass](docs/FreeFormObjectTestClass.md) + - [FreeFormObjectTestClassProperties](docs/FreeFormObjectTestClassProperties.md) - [Fruit](docs/Fruit.md) - [FruitReq](docs/FruitReq.md) - [GmFruit](docs/GmFruit.md) diff --git a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml index 131f50a91650..7170d2f6afb9 100644 --- a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml @@ -1117,6 +1117,20 @@ paths: x-content-type: application/json x-accepts: - application/json + /fake/get-free-form-object: + get: + description: Get a free form object or Json string + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObjectTestClass' + description: Success + tags: + - fake + x-accepts: + - application/json /fake/test-query-parameters: put: description: To test the collection format in query parameters @@ -2134,6 +2148,16 @@ components: $ref: '#/components/schemas/File' type: array type: object + FreeFormObjectTestClass: + example: + name: name + properties: FreeFormObjectTestClass_properties + properties: + name: + type: string + properties: + $ref: '#/components/schemas/FreeFormObjectTestClass_properties' + type: object File: description: Must be named `File` for test. example: @@ -2881,6 +2905,11 @@ components: required: - requiredFile type: object + FreeFormObjectTestClass_properties: + oneOf: + - type: string + - additionalProperties: true + type: object ArrayOfInlineAllOf_array_allof_dog_property_inner: allOf: - properties: diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index 97e59270c5a8..18f99688c925 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -4,6 +4,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | Method | HTTP request | Description | |------------- | ------------- | -------------| +| [**fakeGetFreeFormObjectGet**](FakeApi.md#fakeGetFreeFormObjectGet) | **GET** /fake/get-free-form-object | | | [**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | | | [**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | | | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | @@ -26,6 +27,64 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**testStringMapReference**](FakeApi.md#testStringMapReference) | **POST** /fake/stringMap-reference | test referenced string map | + +# **fakeGetFreeFormObjectGet** +> FreeFormObjectTestClass fakeGetFreeFormObjectGet() + + + +Get a free form object or Json string + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.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 { + FreeFormObjectTestClass result = apiInstance.fakeGetFreeFormObjectGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeGetFreeFormObjectGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**FreeFormObjectTestClass**](FreeFormObjectTestClass.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Success | - | + # **fakeOuterBooleanSerialize** > Boolean fakeOuterBooleanSerialize(body) diff --git a/samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClass.md b/samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClass.md new file mode 100644 index 000000000000..3bb6144bc90b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClass.md @@ -0,0 +1,14 @@ + + +# FreeFormObjectTestClass + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**name** | **String** | | [optional] | +|**properties** | [**FreeFormObjectTestClassProperties**](FreeFormObjectTestClassProperties.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClassProperties.md b/samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClassProperties.md new file mode 100644 index 000000000000..8a7c9d2838a3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/FreeFormObjectTestClassProperties.md @@ -0,0 +1,12 @@ + + +# FreeFormObjectTestClassProperties + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + 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 60c3ef11d94b..69d7ec7bf943 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 @@ -273,6 +273,8 @@ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, Stri gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Foo.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.FooGetDefaultResponse.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.FormatTest.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.FreeFormObjectTestClass.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.FreeFormObjectTestClassProperties.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Fruit.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.FruitReq.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.GmFruit.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 c2e2176d5f0e..664a08c41d6f 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 @@ -31,6 +31,7 @@ import org.openapitools.client.model.Client; import java.io.File; import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.FreeFormObjectTestClass; import org.openapitools.client.model.HealthCheckResult; import java.time.LocalDate; import org.openapitools.client.model.ModelApiResponse; @@ -83,6 +84,119 @@ public void setCustomBaseUrl(String customBaseUrl) { this.localCustomBaseUrl = customBaseUrl; } + /** + * Build call for fakeGetFreeFormObjectGet + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 Success -
+ */ + public okhttp3.Call fakeGetFreeFormObjectGetCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/get-free-form-object"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeGetFreeFormObjectGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return fakeGetFreeFormObjectGetCall(_callback); + + } + + /** + * + * Get a free form object or Json string + * @return FreeFormObjectTestClass + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 Success -
+ */ + public FreeFormObjectTestClass fakeGetFreeFormObjectGet() throws ApiException { + ApiResponse localVarResp = fakeGetFreeFormObjectGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * Get a free form object or Json string + * @return ApiResponse<FreeFormObjectTestClass> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
Status Code Description Response Headers
200 Success -
+ */ + public ApiResponse fakeGetFreeFormObjectGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fakeGetFreeFormObjectGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Get a free form object or Json string + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
Status Code Description Response Headers
200 Success -
+ */ + public okhttp3.Call fakeGetFreeFormObjectGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeGetFreeFormObjectGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } /** * Build call for fakeOuterBooleanSerialize * @param body Input boolean as post body (optional) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java new file mode 100644 index 000000000000..335b40973cf7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClass.java @@ -0,0 +1,318 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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 org.openapitools.client.model.FreeFormObjectTestClassProperties; + +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.lang.reflect.Type; +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; + +/** + * FreeFormObjectTestClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", comments = "Generator version: 7.6.0-SNAPSHOT") +public class FreeFormObjectTestClass { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private String name; + + public static final String SERIALIZED_NAME_PROPERTIES = "properties"; + @SerializedName(SERIALIZED_NAME_PROPERTIES) + private FreeFormObjectTestClassProperties properties; + + public FreeFormObjectTestClass() { + } + + public FreeFormObjectTestClass name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + public FreeFormObjectTestClass properties(FreeFormObjectTestClassProperties properties) { + this.properties = properties; + return this; + } + + /** + * Get properties + * @return properties + **/ + @javax.annotation.Nullable + public FreeFormObjectTestClassProperties getProperties() { + return properties; + } + + public void setProperties(FreeFormObjectTestClassProperties properties) { + this.properties = properties; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the FreeFormObjectTestClass instance itself + */ + public FreeFormObjectTestClass putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FreeFormObjectTestClass freeFormObjectTestClass = (FreeFormObjectTestClass) o; + return Objects.equals(this.name, freeFormObjectTestClass.name) && + Objects.equals(this.properties, freeFormObjectTestClass.properties)&& + Objects.equals(this.additionalProperties, freeFormObjectTestClass.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(name, properties, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FreeFormObjectTestClass {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" properties: ").append(toIndentedString(properties)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + 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(); + openapiFields.add("name"); + openapiFields.add("properties"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to FreeFormObjectTestClass + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!FreeFormObjectTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in FreeFormObjectTestClass is not found in the empty JSON string", FreeFormObjectTestClass.openapiRequiredFields.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // validate the optional field `properties` + if (jsonObj.get("properties") != null && !jsonObj.get("properties").isJsonNull()) { + FreeFormObjectTestClassProperties.validateJsonElement(jsonObj.get("properties")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FreeFormObjectTestClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FreeFormObjectTestClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(FreeFormObjectTestClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FreeFormObjectTestClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + JsonElement jsonElement = gson.toJsonTree(entry.getValue()); + if (jsonElement.isJsonArray()) { + obj.add(entry.getKey(), jsonElement.getAsJsonArray()); + } else { + obj.add(entry.getKey(), jsonElement.getAsJsonObject()); + } + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public FreeFormObjectTestClass read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + FreeFormObjectTestClass instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of FreeFormObjectTestClass given an JSON string + * + * @param jsonString JSON string + * @return An instance of FreeFormObjectTestClass + * @throws IOException if the JSON string is invalid with respect to FreeFormObjectTestClass + */ + public static FreeFormObjectTestClass fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FreeFormObjectTestClass.class); + } + + /** + * Convert an instance of FreeFormObjectTestClass to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java new file mode 100644 index 000000000000..9ac1b95f8186 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FreeFormObjectTestClassProperties.java @@ -0,0 +1,282 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Map; + + + +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.6.0-SNAPSHOT") +public class FreeFormObjectTestClassProperties extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(FreeFormObjectTestClassProperties.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FreeFormObjectTestClassProperties.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FreeFormObjectTestClassProperties' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + final Type typeInstance = new TypeToken>(){}.getType(); + final TypeAdapter> adapterMapStringObject = (TypeAdapter>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FreeFormObjectTestClassProperties value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type `String` + if (value.getActualInstance() instanceof String) { + JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive(); + elementAdapter.write(out, primitive); + return; + } + // check if the actual instance is of the type `Map` + if (value.getActualInstance() instanceof Map) { + JsonObject object = adapterMapStringObject.toJsonTree((Map)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, object); + return; + } + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Map, String"); + } + + @Override + public FreeFormObjectTestClassProperties read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + // deserialize Map + try { + // validate the JSON object to see if any exception is thrown + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + + actualAdapter = adapterMapStringObject; + match++; + log.log(Level.FINER, "Input data matches schema 'Map'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Map failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Map'", e); + } + + if (match == 1) { + FreeFormObjectTestClassProperties ret = new FreeFormObjectTestClassProperties(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for FreeFormObjectTestClassProperties: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap>(); + + public FreeFormObjectTestClassProperties() { + super("oneOf", Boolean.FALSE); + } + + public FreeFormObjectTestClassProperties(Map o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public FreeFormObjectTestClassProperties(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("String", String.class); + schemas.put("Map", Map.class); + } + + @Override + public Map> getSchemas() { + return FreeFormObjectTestClassProperties.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Map, String + * + * It could be an instance of the 'oneOf' schemas. + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Map) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Map, String"); + } + + /** + * Get the actual instance, which can be the following: + * Map, String + * + * @return The actual instance (Map, String) + */ + @SuppressWarnings("unchecked") + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + /** + * Get the actual instance of `Map`. If the actual instance is not `Map`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Map` + * @throws ClassCastException if the instance is not `Map` + */ + public Map getMapStringObject() throws ClassCastException { + return (Map)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 FreeFormObjectTestClassProperties + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + // validate oneOf schemas one by one + int validCount = 0; + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with String + try { + if (!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + // continue to the next one + } + // validate the json string with Map + try { + if (!jsonElement.isJsonObject()) { + throw new IllegalArgumentException(String.format("Expected json element to be a object type in the JSON string but got `%s`", jsonElement.toString())); + } + + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for Map failed with `%s`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for FreeFormObjectTestClassProperties with oneOf schemas: Map, String. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString())); + } + } + + /** + * Create an instance of FreeFormObjectTestClassProperties given an JSON string + * + * @param jsonString JSON string + * @return An instance of FreeFormObjectTestClassProperties + * @throws IOException if the JSON string is invalid with respect to FreeFormObjectTestClassProperties + */ + public static FreeFormObjectTestClassProperties fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, FreeFormObjectTestClassProperties.class); + } + + /** + * Convert an instance of FreeFormObjectTestClassProperties to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-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 978195ccf6de..765e7b71c77a 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 @@ -37,6 +37,28 @@ public void setup() { order = new Order(); } + @Test + public void testOneOfFreeFormObject() { + final Map map = new LinkedHashMap<>(); + map.put("someString", "abc"); + map.put("someBoolean", false); + + final String json1 = "{\"someString\":\"abc\",\"someBoolean\":false}"; + final FreeFormObjectTestClassProperties properties = new FreeFormObjectTestClassProperties(); + properties.setActualInstance(map); + + assertEquals(json1, json.serialize(properties)); + assertEquals(json.deserialize(json1, FreeFormObjectTestClassProperties.class), properties); + + + final String json2 = "\"abc\""; + final FreeFormObjectTestClassProperties properties2 = new FreeFormObjectTestClassProperties(); + properties2.setActualInstance("abc"); + + assertEquals(json2, json.serialize(properties2)); + assertEquals(json.deserialize(json2, FreeFormObjectTestClassProperties.class), properties2); + } + @Test public void testSqlDateTypeAdapter() { final String str = "\"2015-11-07\""; diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassPropertiesTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassPropertiesTest.java new file mode 100644 index 000000000000..32a85ee296b7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassPropertiesTest.java @@ -0,0 +1,34 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class 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.Map; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FreeFormObjectTestClassProperties + */ +public class FreeFormObjectTestClassPropertiesTest { + private final FreeFormObjectTestClassProperties model = new FreeFormObjectTestClassProperties(); + + /** + * Model tests for FreeFormObjectTestClassProperties + */ + @Test + public void testFreeFormObjectTestClassProperties() { + // TODO: test FreeFormObjectTestClassProperties + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassTest.java new file mode 100644 index 000000000000..3d2f22b98de3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FreeFormObjectTestClassTest.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.client.model.FreeFormObjectTestClassProperties; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for FreeFormObjectTestClass + */ +public class FreeFormObjectTestClassTest { + private final FreeFormObjectTestClass model = new FreeFormObjectTestClass(); + + /** + * Model tests for FreeFormObjectTestClass + */ + @Test + public void testFreeFormObjectTestClass() { + // TODO: test FreeFormObjectTestClass + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'properties' + */ + @Test + public void propertiesTest() { + // TODO: test properties + } + +}