[Java][Client] Fix #12556 Support primitives and arrays in oneOf (#13897)

* [Java][Client] Fix #12556 Support primitives and arrays in oneOf

* Regenerate petstore samples

* Regenerate petstore test samples

* Treat 'BigDecimal' as primtive datatype

* Fix integration tests
This commit is contained in:
karzang
2023-06-29 10:46:55 +02:00
committed by GitHub
parent b2280e23f7
commit e9d98666a1
282 changed files with 4701 additions and 2670 deletions

View File

@@ -75,6 +75,7 @@ docs/Pig.md
docs/Quadrilateral.md
docs/QuadrilateralInterface.md
docs/ReadOnlyFirst.md
docs/Scalar.md
docs/ScaleneTriangle.md
docs/Shape.md
docs/ShapeInterface.md
@@ -87,6 +88,9 @@ docs/Triangle.md
docs/TriangleInterface.md
docs/User.md
docs/UserApi.md
docs/Value.md
docs/ValuesApi.md
docs/Variable.md
docs/Whale.md
docs/Zebra.md
git_push.sh
@@ -118,6 +122,7 @@ src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java
src/main/java/org/openapitools/client/api/PetApi.java
src/main/java/org/openapitools/client/api/StoreApi.java
src/main/java/org/openapitools/client/api/UserApi.java
src/main/java/org/openapitools/client/api/ValuesApi.java
src/main/java/org/openapitools/client/auth/ApiKeyAuth.java
src/main/java/org/openapitools/client/auth/Authentication.java
src/main/java/org/openapitools/client/auth/HttpBasicAuth.java
@@ -192,6 +197,7 @@ src/main/java/org/openapitools/client/model/Pig.java
src/main/java/org/openapitools/client/model/Quadrilateral.java
src/main/java/org/openapitools/client/model/QuadrilateralInterface.java
src/main/java/org/openapitools/client/model/ReadOnlyFirst.java
src/main/java/org/openapitools/client/model/Scalar.java
src/main/java/org/openapitools/client/model/ScaleneTriangle.java
src/main/java/org/openapitools/client/model/Shape.java
src/main/java/org/openapitools/client/model/ShapeInterface.java
@@ -202,5 +208,7 @@ src/main/java/org/openapitools/client/model/Tag.java
src/main/java/org/openapitools/client/model/Triangle.java
src/main/java/org/openapitools/client/model/TriangleInterface.java
src/main/java/org/openapitools/client/model/User.java
src/main/java/org/openapitools/client/model/Value.java
src/main/java/org/openapitools/client/model/Variable.java
src/main/java/org/openapitools/client/model/Whale.java
src/main/java/org/openapitools/client/model/Zebra.java

View File

@@ -152,6 +152,7 @@ Class | Method | HTTP request | Description
*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system
*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session
*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user
*ValuesApi* | [**getSomeValues**](docs/ValuesApi.md#getSomeValues) | **GET** /values | Get some primitive variable values
## Documentation for Models
@@ -221,6 +222,7 @@ Class | Method | HTTP request | Description
- [Quadrilateral](docs/Quadrilateral.md)
- [QuadrilateralInterface](docs/QuadrilateralInterface.md)
- [ReadOnlyFirst](docs/ReadOnlyFirst.md)
- [Scalar](docs/Scalar.md)
- [ScaleneTriangle](docs/ScaleneTriangle.md)
- [Shape](docs/Shape.md)
- [ShapeInterface](docs/ShapeInterface.md)
@@ -231,6 +233,8 @@ Class | Method | HTTP request | Description
- [Triangle](docs/Triangle.md)
- [TriangleInterface](docs/TriangleInterface.md)
- [User](docs/User.md)
- [Value](docs/Value.md)
- [Variable](docs/Variable.md)
- [Whale](docs/Whale.md)
- [Zebra](docs/Zebra.md)

View File

@@ -1132,6 +1132,23 @@ paths:
tags:
- fake
x-accepts: application/json
/values:
get:
description: ""
operationId: getSomeValues
responses:
"200":
content:
application/json:
schema:
$ref: '#/components/schemas/Variable'
description: successful operation
"400":
description: Invalid Value
summary: Get some primitive variable values
tags:
- values
x-accepts: application/json
components:
requestBodies:
UserArray:
@@ -2217,6 +2234,37 @@ components:
items:
type: string
type: array
Variable:
description: Value object
example:
name: variable_1
value: null
properties:
name:
example: variable_1
type: string
value:
$ref: '#/components/schemas/Value'
required:
- name
- value
Value:
oneOf:
- $ref: '#/components/schemas/Scalar'
- $ref: '#/components/schemas/Array'
Scalar:
description: Values of scalar type
oneOf:
- maxLength: 1089
type: string
- type: number
- type: boolean
Array:
description: Values of array type
items:
$ref: '#/components/schemas/Scalar'
minItems: 1
type: array
_foo_get_default_response:
example:
string:

View File

@@ -247,7 +247,7 @@ public class Example {
### Return type
[**BigDecimal**](BigDecimal.md)
**BigDecimal**
### Authorization

View File

@@ -0,0 +1,13 @@
# Scalar
Values of scalar type
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|

View File

@@ -0,0 +1,12 @@
# Value
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|

View File

@@ -0,0 +1,68 @@
# ValuesApi
All URIs are relative to *http://petstore.swagger.io:80/v2*
| Method | HTTP request | Description |
|------------- | ------------- | -------------|
| [**getSomeValues**](ValuesApi.md#getSomeValues) | **GET** /values | Get some primitive variable values |
<a id="getSomeValues"></a>
# **getSomeValues**
> Variable getSomeValues()
Get some primitive variable values
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;
import org.openapitools.client.api.ValuesApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io:80/v2");
ValuesApi apiInstance = new ValuesApi(defaultClient);
try {
Variable result = apiInstance.getSomeValues();
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling ValuesApi#getSomeValues");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
[**Variable**](Variable.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid Value | - |

View File

@@ -0,0 +1,15 @@
# Variable
Value object
## Properties
| Name | Type | Description | Notes |
|------------ | ------------- | ------------- | -------------|
|**name** | **String** | | |
|**value** | [**Value**](Value.md) | | |

View File

@@ -287,6 +287,7 @@ public class JSON {
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Quadrilateral.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.QuadrilateralInterface.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ReadOnlyFirst.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Scalar.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ScaleneTriangle.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Shape.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ShapeInterface.CustomTypeAdapterFactory());
@@ -297,6 +298,8 @@ public class JSON {
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Triangle.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.TriangleInterface.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.User.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Value.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Variable.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Whale.CustomTypeAdapterFactory());
gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Zebra.CustomTypeAdapterFactory());
gson = gsonBuilder.create();

View File

@@ -0,0 +1,192 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api;
import org.openapitools.client.ApiCallback;
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.ApiResponse;
import org.openapitools.client.Configuration;
import org.openapitools.client.Pair;
import org.openapitools.client.ProgressRequestBody;
import org.openapitools.client.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import org.openapitools.client.model.Variable;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ValuesApi {
private ApiClient localVarApiClient;
private int localHostIndex;
private String localCustomBaseUrl;
public ValuesApi() {
this(Configuration.getDefaultApiClient());
}
public ValuesApi(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public int getHostIndex() {
return localHostIndex;
}
public void setHostIndex(int hostIndex) {
this.localHostIndex = hostIndex;
}
public String getCustomBaseUrl() {
return localCustomBaseUrl;
}
public void setCustomBaseUrl(String customBaseUrl) {
this.localCustomBaseUrl = customBaseUrl;
}
/**
* Build call for getSomeValues
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Value </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getSomeValuesCall(final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/values";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { };
return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call getSomeValuesValidateBeforeCall(final ApiCallback _callback) throws ApiException {
return getSomeValuesCall(_callback);
}
/**
* Get some primitive variable values
*
* @return Variable
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Value </td><td> - </td></tr>
</table>
*/
public Variable getSomeValues() throws ApiException {
ApiResponse<Variable> localVarResp = getSomeValuesWithHttpInfo();
return localVarResp.getData();
}
/**
* Get some primitive variable values
*
* @return ApiResponse&lt;Variable&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Value </td><td> - </td></tr>
</table>
*/
public ApiResponse<Variable> getSomeValuesWithHttpInfo() throws ApiException {
okhttp3.Call localVarCall = getSomeValuesValidateBeforeCall(null);
Type localVarReturnType = new TypeToken<Variable>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
}
/**
* Get some primitive variable values (asynchronously)
*
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> successful operation </td><td> - </td></tr>
<tr><td> 400 </td><td> Invalid Value </td><td> - </td></tr>
</table>
*/
public okhttp3.Call getSomeValuesAsync(final ApiCallback<Variable> _callback) throws ApiException {
okhttp3.Call localVarCall = getSomeValuesValidateBeforeCall(_callback);
Type localVarReturnType = new TypeToken<Variable>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);
return localVarCall;
}
}

View File

@@ -420,17 +420,18 @@ public class AdditionalPropertiesClass {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesClass
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to AdditionalPropertiesClass
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesClass is not found in the empty JSON string", AdditionalPropertiesClass.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@@ -470,8 +471,9 @@ public class AdditionalPropertiesClass {
@Override
public AdditionalPropertiesClass read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
AdditionalPropertiesClass instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -208,25 +208,25 @@ public class Animal {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Animal
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Animal
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Animal.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Animal.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Animal is not found in the empty JSON string", Animal.openapiRequiredFields.toString()));
}
}
String discriminatorValue = jsonObj.get("className").getAsString();
String discriminatorValue = jsonElement.getAsJsonObject().get("className").getAsString();
switch (discriminatorValue) {
case "Cat":
Cat.validateJsonObject(jsonObj);
Cat.validateJsonElement(jsonElement);
break;
case "Dog":
Dog.validateJsonObject(jsonObj);
Dog.validateJsonElement(jsonElement);
break;
default:
throw new IllegalArgumentException(String.format("The value of the `className` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue));

View File

@@ -206,17 +206,18 @@ public class Apple {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Apple
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Apple
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Apple.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Apple.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Apple is not found in the empty JSON string", Apple.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("cultivar") != null && !jsonObj.get("cultivar").isJsonNull()) && !jsonObj.get("cultivar").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `cultivar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("cultivar").toString()));
}
@@ -262,8 +263,9 @@ public class Apple {
@Override
public Apple read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Apple instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -161,32 +161,33 @@ public class AppleReq {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AppleReq
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to AppleReq
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!AppleReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!AppleReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in AppleReq is not found in the empty JSON string", AppleReq.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
Set<Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AppleReq.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AppleReq` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AppleReq` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : AppleReq.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("cultivar").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `cultivar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("cultivar").toString()));
}
@@ -212,9 +213,9 @@ public class AppleReq {
@Override
public AppleReq read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();

View File

@@ -224,17 +224,18 @@ public class ArrayDefault {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayDefault
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ArrayDefault
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ArrayDefault.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ArrayDefault.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayDefault is not found in the empty JSON string", ArrayDefault.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// ensure the optional json data is an array if present
if (jsonObj.get("WithDefaultEmptyBracket") != null && !jsonObj.get("WithDefaultEmptyBracket").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `WithDefaultEmptyBracket` to be an array in the JSON string but got `%s`", jsonObj.get("WithDefaultEmptyBracket").toString()));
@@ -282,8 +283,9 @@ public class ArrayDefault {
@Override
public ArrayDefault read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ArrayDefault instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -189,17 +189,18 @@ public class ArrayOfArrayOfNumberOnly {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayOfArrayOfNumberOnly
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ArrayOfArrayOfNumberOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfArrayOfNumberOnly is not found in the empty JSON string", ArrayOfArrayOfNumberOnly.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// ensure the optional json data is an array if present
if (jsonObj.get("ArrayArrayNumber") != null && !jsonObj.get("ArrayArrayNumber").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `ArrayArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayArrayNumber").toString()));
@@ -243,8 +244,9 @@ public class ArrayOfArrayOfNumberOnly {
@Override
public ArrayOfArrayOfNumberOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ArrayOfArrayOfNumberOnly instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -246,24 +246,25 @@ public class ArrayOfInlineAllOf {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayOfInlineAllOf
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ArrayOfInlineAllOf
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ArrayOfInlineAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ArrayOfInlineAllOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfInlineAllOf is not found in the empty JSON string", ArrayOfInlineAllOf.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : ArrayOfInlineAllOf.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("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()));
}
@@ -277,7 +278,7 @@ public class ArrayOfInlineAllOf {
// validate the optional field `array_allof_dog_property` (array)
for (int i = 0; i < jsonArrayarrayAllofDogProperty.size(); i++) {
ArrayOfInlineAllOfArrayAllofDogPropertyInner.validateJsonObject(jsonArrayarrayAllofDogProperty.get(i).getAsJsonObject());
ArrayOfInlineAllOfArrayAllofDogPropertyInner.validateJsonElement(jsonArrayarrayAllofDogProperty.get(i));
};
}
}
@@ -320,8 +321,9 @@ public class ArrayOfInlineAllOf {
@Override
public ArrayOfInlineAllOf read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ArrayOfInlineAllOf instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -206,17 +206,18 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInner {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayOfInlineAllOfArrayAllofDogPropertyInner
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ArrayOfInlineAllOfArrayAllofDogPropertyInner
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfInlineAllOfArrayAllofDogPropertyInner is not found in the empty JSON string", ArrayOfInlineAllOfArrayAllofDogPropertyInner.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("breed") != null && !jsonObj.get("breed").isJsonNull()) && !jsonObj.get("breed").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `breed` to be a primitive type in the JSON string but got `%s`", jsonObj.get("breed").toString()));
}
@@ -262,8 +263,9 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInner {
@Override
public ArrayOfInlineAllOfArrayAllofDogPropertyInner read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ArrayOfInlineAllOfArrayAllofDogPropertyInner instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -178,17 +178,18 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 is not found in the empty JSON string", ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("color") != null && !jsonObj.get("color").isJsonNull()) && !jsonObj.get("color").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `color` to be a primitive type in the JSON string but got `%s`", jsonObj.get("color").toString()));
}
@@ -231,8 +232,9 @@ public class ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 {
@Override
public ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ArrayOfInlineAllOfArrayAllofDogPropertyInnerAllOf1 instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -189,17 +189,18 @@ public class ArrayOfNumberOnly {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayOfNumberOnly
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ArrayOfNumberOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfNumberOnly is not found in the empty JSON string", ArrayOfNumberOnly.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// ensure the optional json data is an array if present
if (jsonObj.get("ArrayNumber") != null && !jsonObj.get("ArrayNumber").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `ArrayNumber` to be an array in the JSON string but got `%s`", jsonObj.get("ArrayNumber").toString()));
@@ -243,8 +244,9 @@ public class ArrayOfNumberOnly {
@Override
public ArrayOfNumberOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ArrayOfNumberOnly instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -261,17 +261,18 @@ public class ArrayTest {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayTest
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ArrayTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ArrayTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ArrayTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayTest is not found in the empty JSON string", ArrayTest.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// ensure the optional json data is an array if present
if (jsonObj.get("array_of_string") != null && !jsonObj.get("array_of_string").isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected the field `array_of_string` to be an array in the JSON string but got `%s`", jsonObj.get("array_of_string").toString()));
@@ -323,8 +324,9 @@ public class ArrayTest {
@Override
public ArrayTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ArrayTest instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -179,17 +179,18 @@ public class Banana {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Banana
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Banana
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Banana.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Banana.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Banana is not found in the empty JSON string", Banana.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@@ -229,8 +230,9 @@ public class Banana {
@Override
public Banana read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Banana instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -162,32 +162,33 @@ public class BananaReq {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to BananaReq
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to BananaReq
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!BananaReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!BananaReq.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in BananaReq is not found in the empty JSON string", BananaReq.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
Set<Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!BananaReq.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BananaReq` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BananaReq` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : BananaReq.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@@ -210,9 +211,9 @@ public class BananaReq {
@Override
public BananaReq read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();

View File

@@ -179,24 +179,25 @@ public class BasquePig {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to BasquePig
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to BasquePig
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!BasquePig.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!BasquePig.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in BasquePig is not found in the empty JSON string", BasquePig.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : BasquePig.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("className").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString()));
}
@@ -239,8 +240,9 @@ public class BasquePig {
@Override
public BasquePig read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
BasquePig instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -318,17 +318,18 @@ public class Capitalization {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Capitalization
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Capitalization
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Capitalization.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Capitalization.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Capitalization is not found in the empty JSON string", Capitalization.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("smallCamel") != null && !jsonObj.get("smallCamel").isJsonNull()) && !jsonObj.get("smallCamel").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `smallCamel` to be a primitive type in the JSON string but got `%s`", jsonObj.get("smallCamel").toString()));
}
@@ -386,8 +387,9 @@ public class Capitalization {
@Override
public Capitalization read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Capitalization instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -185,22 +185,22 @@ public class Cat extends Animal {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Cat
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Cat
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Cat.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Cat.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Cat is not found in the empty JSON string", Cat.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Cat.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
}
@@ -242,8 +242,9 @@ public class Cat extends Animal {
@Override
public Cat read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Cat instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -207,24 +207,25 @@ public class Category {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Category
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Category
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Category.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Category.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("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()));
}
@@ -267,8 +268,9 @@ public class Category {
@Override
public Category read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Category instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -178,17 +178,18 @@ public class ClassModel {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ClassModel
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ClassModel
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ClassModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ClassModel.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ClassModel is not found in the empty JSON string", ClassModel.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("_class") != null && !jsonObj.get("_class").isJsonNull()) && !jsonObj.get("_class").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `_class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_class").toString()));
}
@@ -231,8 +232,9 @@ public class ClassModel {
@Override
public ClassModel read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ClassModel instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -178,17 +178,18 @@ public class Client {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Client
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Client
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Client.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Client.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Client is not found in the empty JSON string", Client.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("client") != null && !jsonObj.get("client").isJsonNull()) && !jsonObj.get("client").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `client` to be a primitive type in the JSON string but got `%s`", jsonObj.get("client").toString()));
}
@@ -231,8 +232,9 @@ public class Client {
@Override
public Client read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Client instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -208,24 +208,25 @@ public class ComplexQuadrilateral {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ComplexQuadrilateral
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ComplexQuadrilateral
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ComplexQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ComplexQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ComplexQuadrilateral is not found in the empty JSON string", ComplexQuadrilateral.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : ComplexQuadrilateral.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("shapeType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString()));
}
@@ -271,8 +272,9 @@ public class ComplexQuadrilateral {
@Override
public ComplexQuadrilateral read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ComplexQuadrilateral instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -179,24 +179,25 @@ public class DanishPig {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to DanishPig
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to DanishPig
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!DanishPig.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!DanishPig.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in DanishPig is not found in the empty JSON string", DanishPig.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : DanishPig.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("className").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString()));
}
@@ -239,8 +240,9 @@ public class DanishPig {
@Override
public DanishPig read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
DanishPig instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -180,17 +180,18 @@ public class DeprecatedObject {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to DeprecatedObject
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to DeprecatedObject
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!DeprecatedObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!DeprecatedObject.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in DeprecatedObject is not found in the empty JSON string", DeprecatedObject.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()));
}
@@ -233,8 +234,9 @@ public class DeprecatedObject {
@Override
public DeprecatedObject read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
DeprecatedObject instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -185,22 +185,22 @@ public class Dog extends Animal {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Dog
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Dog
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Dog.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Dog.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Dog is not found in the empty JSON string", Dog.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Dog.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
}
@@ -242,8 +242,9 @@ public class Dog extends Animal {
@Override
public Dog read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Dog instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -242,36 +242,37 @@ public class Drawing {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Drawing
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Drawing
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Drawing.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Drawing.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Drawing is not found in the empty JSON string", Drawing.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
Set<Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Drawing.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Drawing` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Drawing` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `mainShape`
if (jsonObj.get("mainShape") != null && !jsonObj.get("mainShape").isJsonNull()) {
Shape.validateJsonObject(jsonObj.getAsJsonObject("mainShape"));
Shape.validateJsonElement(jsonObj.get("mainShape"));
}
// validate the optional field `shapeOrNull`
if (jsonObj.get("shapeOrNull") != null && !jsonObj.get("shapeOrNull").isJsonNull()) {
ShapeOrNull.validateJsonObject(jsonObj.getAsJsonObject("shapeOrNull"));
ShapeOrNull.validateJsonElement(jsonObj.get("shapeOrNull"));
}
// validate the optional field `nullableShape`
if (jsonObj.get("nullableShape") != null && !jsonObj.get("nullableShape").isJsonNull()) {
NullableShape.validateJsonObject(jsonObj.getAsJsonObject("nullableShape"));
NullableShape.validateJsonElement(jsonObj.get("nullableShape"));
}
if (jsonObj.get("shapes") != null && !jsonObj.get("shapes").isJsonNull()) {
JsonArray jsonArrayshapes = jsonObj.getAsJsonArray("shapes");
@@ -283,7 +284,7 @@ public class Drawing {
// validate the optional field `shapes` (array)
for (int i = 0; i < jsonArrayshapes.size(); i++) {
Shape.validateJsonObject(jsonArrayshapes.get(i).getAsJsonObject());
Shape.validateJsonElement(jsonArrayshapes.get(i));
};
}
}
@@ -309,9 +310,9 @@ public class Drawing {
@Override
public Drawing read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();

View File

@@ -310,17 +310,18 @@ public class EnumArrays {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to EnumArrays
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to EnumArrays
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!EnumArrays.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!EnumArrays.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in EnumArrays is not found in the empty JSON string", EnumArrays.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString()));
}
@@ -367,8 +368,9 @@ public class EnumArrays {
@Override
public EnumArrays read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
EnumArrays instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -226,22 +226,22 @@ public class EnumStringDiscriminator {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to EnumStringDiscriminator
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to EnumStringDiscriminator
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!EnumStringDiscriminator.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!EnumStringDiscriminator.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in EnumStringDiscriminator is not found in the empty JSON string", EnumStringDiscriminator.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : EnumStringDiscriminator.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
}
@@ -283,8 +283,9 @@ public class EnumStringDiscriminator {
@Override
public EnumStringDiscriminator read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
EnumStringDiscriminator instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -658,24 +658,25 @@ public class EnumTest {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to EnumTest
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to EnumTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!EnumTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!EnumTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in EnumTest is not found in the empty JSON string", EnumTest.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : EnumTest.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString()));
}
@@ -721,8 +722,9 @@ public class EnumTest {
@Override
public EnumTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
EnumTest instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -208,24 +208,25 @@ public class EquilateralTriangle {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to EquilateralTriangle
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to EquilateralTriangle
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!EquilateralTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!EquilateralTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in EquilateralTriangle is not found in the empty JSON string", EquilateralTriangle.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : EquilateralTriangle.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("shapeType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString()));
}
@@ -271,8 +272,9 @@ public class EquilateralTriangle {
@Override
public EquilateralTriangle read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
EquilateralTriangle instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -217,20 +217,21 @@ public class FileSchemaTestClass {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to FileSchemaTestClass
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to FileSchemaTestClass
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!FileSchemaTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!FileSchemaTestClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in FileSchemaTestClass is not found in the empty JSON string", FileSchemaTestClass.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `file`
if (jsonObj.get("file") != null && !jsonObj.get("file").isJsonNull()) {
ModelFile.validateJsonObject(jsonObj.getAsJsonObject("file"));
ModelFile.validateJsonElement(jsonObj.get("file"));
}
if (jsonObj.get("files") != null && !jsonObj.get("files").isJsonNull()) {
JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files");
@@ -242,7 +243,7 @@ public class FileSchemaTestClass {
// validate the optional field `files` (array)
for (int i = 0; i < jsonArrayfiles.size(); i++) {
ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject());
ModelFile.validateJsonElement(jsonArrayfiles.get(i));
};
}
}
@@ -285,8 +286,9 @@ public class FileSchemaTestClass {
@Override
public FileSchemaTestClass read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
FileSchemaTestClass instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -178,17 +178,18 @@ public class Foo {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Foo
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Foo
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Foo.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Foo.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Foo is not found in the empty JSON string", Foo.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString()));
}
@@ -231,8 +232,9 @@ public class Foo {
@Override
public Foo read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Foo instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -179,20 +179,21 @@ public class FooGetDefaultResponse {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to FooGetDefaultResponse
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to FooGetDefaultResponse
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!FooGetDefaultResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!FooGetDefaultResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in FooGetDefaultResponse is not found in the empty JSON string", FooGetDefaultResponse.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `string`
if (jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) {
Foo.validateJsonObject(jsonObj.getAsJsonObject("string"));
Foo.validateJsonElement(jsonObj.get("string"));
}
}
@@ -233,8 +234,9 @@ public class FooGetDefaultResponse {
@Override
public FooGetDefaultResponse read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
FooGetDefaultResponse instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -645,24 +645,25 @@ public class FormatTest {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to FormatTest
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to FormatTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!FormatTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!FormatTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in FormatTest is not found in the empty JSON string", FormatTest.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : FormatTest.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("string") != null && !jsonObj.get("string").isJsonNull()) && !jsonObj.get("string").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string").toString()));
}
@@ -720,8 +721,9 @@ public class FormatTest {
@Override
public FormatTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
FormatTest instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -35,6 +35,7 @@ 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;
@@ -54,6 +55,7 @@ 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;
@@ -83,25 +85,23 @@ public class Fruit extends AbstractOpenApiSchema {
// check if the actual instance is of the type `Apple`
if (value.getActualInstance() instanceof Apple) {
JsonObject obj = adapterApple.toJsonTree((Apple)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterApple.toJsonTree((Apple)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `Banana`
if (value.getActualInstance() instanceof Banana) {
JsonObject obj = adapterBanana.toJsonTree((Banana)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterBanana.toJsonTree((Banana)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Apple, Banana");
}
@Override
public Fruit read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
int match = 0;
ArrayList<String> errorMessages = new ArrayList<>();
@@ -109,37 +109,36 @@ public class Fruit extends AbstractOpenApiSchema {
// deserialize Apple
try {
// validate the JSON object to see if any exception is thrown
Apple.validateJsonObject(jsonObject);
actualAdapter = adapterApple;
match++;
log.log(Level.FINER, "Input data matches schema 'Apple'");
// validate the JSON object to see if any exception is thrown
Apple.validateJsonElement(jsonElement);
actualAdapter = adapterApple;
match++;
log.log(Level.FINER, "Input data matches schema 'Apple'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Apple failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Apple'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Apple failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Apple'", e);
}
// deserialize Banana
try {
// validate the JSON object to see if any exception is thrown
Banana.validateJsonObject(jsonObject);
actualAdapter = adapterBanana;
match++;
log.log(Level.FINER, "Input data matches schema 'Banana'");
// validate the JSON object to see if any exception is thrown
Banana.validateJsonElement(jsonElement);
actualAdapter = adapterBanana;
match++;
log.log(Level.FINER, "Input data matches schema 'Banana'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Banana failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Banana'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Banana failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Banana'", e);
}
if (match == 1) {
Fruit ret = new Fruit();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Fruit: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for Fruit: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -216,7 +215,6 @@ public class Fruit extends AbstractOpenApiSchema {
public Apple getApple() throws ClassCastException {
return (Apple)super.getActualInstance();
}
/**
* Get the actual instance of `Banana`. If the actual instance is not `Banana`,
* the ClassCastException will be thrown.
@@ -228,20 +226,19 @@ public class Fruit extends AbstractOpenApiSchema {
return (Banana)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Fruit
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Fruit
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with Apple
try {
Apple.validateJsonObject(jsonObj);
Apple.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Apple failed with `%s`.", e.getMessage()));
@@ -249,14 +246,14 @@ public class Fruit extends AbstractOpenApiSchema {
}
// validate the json string with Banana
try {
Banana.validateJsonObject(jsonObj);
Banana.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Banana failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Fruit with oneOf schemas: Apple, Banana. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for Fruit with oneOf schemas: Apple, Banana. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -35,6 +35,7 @@ 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;
@@ -54,6 +55,7 @@ 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;
@@ -83,25 +85,23 @@ public class FruitReq extends AbstractOpenApiSchema {
// check if the actual instance is of the type `AppleReq`
if (value.getActualInstance() instanceof AppleReq) {
JsonObject obj = adapterAppleReq.toJsonTree((AppleReq)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterAppleReq.toJsonTree((AppleReq)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `BananaReq`
if (value.getActualInstance() instanceof BananaReq) {
JsonObject obj = adapterBananaReq.toJsonTree((BananaReq)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterBananaReq.toJsonTree((BananaReq)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: AppleReq, BananaReq");
}
@Override
public FruitReq read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
int match = 0;
ArrayList<String> errorMessages = new ArrayList<>();
@@ -109,37 +109,36 @@ public class FruitReq extends AbstractOpenApiSchema {
// deserialize AppleReq
try {
// validate the JSON object to see if any exception is thrown
AppleReq.validateJsonObject(jsonObject);
actualAdapter = adapterAppleReq;
match++;
log.log(Level.FINER, "Input data matches schema 'AppleReq'");
// validate the JSON object to see if any exception is thrown
AppleReq.validateJsonElement(jsonElement);
actualAdapter = adapterAppleReq;
match++;
log.log(Level.FINER, "Input data matches schema 'AppleReq'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for AppleReq failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'AppleReq'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for AppleReq failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'AppleReq'", e);
}
// deserialize BananaReq
try {
// validate the JSON object to see if any exception is thrown
BananaReq.validateJsonObject(jsonObject);
actualAdapter = adapterBananaReq;
match++;
log.log(Level.FINER, "Input data matches schema 'BananaReq'");
// validate the JSON object to see if any exception is thrown
BananaReq.validateJsonElement(jsonElement);
actualAdapter = adapterBananaReq;
match++;
log.log(Level.FINER, "Input data matches schema 'BananaReq'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for BananaReq failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'BananaReq'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for BananaReq failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'BananaReq'", e);
}
if (match == 1) {
FruitReq ret = new FruitReq();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for FruitReq: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for FruitReq: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -221,7 +220,6 @@ public class FruitReq extends AbstractOpenApiSchema {
public AppleReq getAppleReq() throws ClassCastException {
return (AppleReq)super.getActualInstance();
}
/**
* Get the actual instance of `BananaReq`. If the actual instance is not `BananaReq`,
* the ClassCastException will be thrown.
@@ -233,20 +231,19 @@ public class FruitReq extends AbstractOpenApiSchema {
return (BananaReq)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to FruitReq
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to FruitReq
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with AppleReq
try {
AppleReq.validateJsonObject(jsonObj);
AppleReq.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for AppleReq failed with `%s`.", e.getMessage()));
@@ -254,14 +251,14 @@ public class FruitReq extends AbstractOpenApiSchema {
}
// validate the json string with BananaReq
try {
BananaReq.validateJsonObject(jsonObj);
BananaReq.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for BananaReq failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for FruitReq with oneOf schemas: AppleReq, BananaReq. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for FruitReq with oneOf schemas: AppleReq, BananaReq. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -101,15 +101,15 @@ public class GmFruit extends AbstractOpenApiSchema {
@Override
public GmFruit read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
// deserialize Apple
try {
// validate the JSON object to see if any exception is thrown
Apple.validateJsonObject(jsonObject);
Apple.validateJsonElement(jsonElement);
log.log(Level.FINER, "Input data matches schema 'Apple'");
GmFruit ret = new GmFruit();
ret.setActualInstance(adapterApple.fromJsonTree(jsonObject));
ret.setActualInstance(adapterApple.fromJsonTree(jsonElement));
return ret;
} catch (Exception e) {
// deserialization failed, continue
@@ -119,10 +119,10 @@ public class GmFruit extends AbstractOpenApiSchema {
// deserialize Banana
try {
// validate the JSON object to see if any exception is thrown
Banana.validateJsonObject(jsonObject);
Banana.validateJsonElement(jsonElement);
log.log(Level.FINER, "Input data matches schema 'Banana'");
GmFruit ret = new GmFruit();
ret.setActualInstance(adapterBanana.fromJsonTree(jsonObject));
ret.setActualInstance(adapterBanana.fromJsonTree(jsonElement));
return ret;
} catch (Exception e) {
// deserialization failed, continue
@@ -130,7 +130,7 @@ public class GmFruit extends AbstractOpenApiSchema {
}
throw new IOException(String.format("Failed deserialization for GmFruit: no class matched. JSON: %s", jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for GmFruit: no class matched. JSON: %s", jsonElement.toString()));
}
}.nullSafe();
}
@@ -221,17 +221,17 @@ public class GmFruit extends AbstractOpenApiSchema {
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to GmFruit
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to GmFruit
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate anyOf schemas one by one
int validCount = 0;
// validate the json string with Apple
try {
Apple.validateJsonObject(jsonObj);
Apple.validateJsonElement(jsonElement);
return; // return earlier as at least one schema is valid with respect to the Json object
//validCount++;
} catch (Exception e) {
@@ -239,14 +239,14 @@ public class GmFruit extends AbstractOpenApiSchema {
}
// validate the json string with Banana
try {
Banana.validateJsonObject(jsonObj);
Banana.validateJsonElement(jsonElement);
return; // return earlier as at least one schema is valid with respect to the Json object
//validCount++;
} catch (Exception e) {
// continue to the next one
}
if (validCount == 0) {
throw new IOException(String.format("The JSON string is invalid for GmFruit with anyOf schemas: Apple, Banana. JSON: %s", jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for GmFruit with anyOf schemas: Apple, Banana. JSON: %s", jsonElement.toString()));
}
}

View File

@@ -180,22 +180,22 @@ public class GrandparentAnimal {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to GrandparentAnimal
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to GrandparentAnimal
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!GrandparentAnimal.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!GrandparentAnimal.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in GrandparentAnimal is not found in the empty JSON string", GrandparentAnimal.openapiRequiredFields.toString()));
}
}
String discriminatorValue = jsonObj.get("pet_type").getAsString();
String discriminatorValue = jsonElement.getAsJsonObject().get("pet_type").getAsString();
switch (discriminatorValue) {
case "ParentPet":
ParentPet.validateJsonObject(jsonObj);
ParentPet.validateJsonElement(jsonElement);
break;
default:
throw new IllegalArgumentException(String.format("The value of the `pet_type` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue));

View File

@@ -198,17 +198,18 @@ public class HasOnlyReadOnly {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to HasOnlyReadOnly
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to HasOnlyReadOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!HasOnlyReadOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in HasOnlyReadOnly is not found in the empty JSON string", HasOnlyReadOnly.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString()));
}
@@ -254,8 +255,9 @@ public class HasOnlyReadOnly {
@Override
public HasOnlyReadOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
HasOnlyReadOnly instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -190,17 +190,18 @@ public class HealthCheckResult {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to HealthCheckResult
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to HealthCheckResult
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!HealthCheckResult.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!HealthCheckResult.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in HealthCheckResult is not found in the empty JSON string", HealthCheckResult.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("NullableMessage") != null && !jsonObj.get("NullableMessage").isJsonNull()) && !jsonObj.get("NullableMessage").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `NullableMessage` to be a primitive type in the JSON string but got `%s`", jsonObj.get("NullableMessage").toString()));
}
@@ -243,8 +244,9 @@ public class HealthCheckResult {
@Override
public HealthCheckResult read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
HealthCheckResult instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -162,32 +162,33 @@ public class IsoscelesTriangle {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to IsoscelesTriangle
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to IsoscelesTriangle
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!IsoscelesTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!IsoscelesTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in IsoscelesTriangle is not found in the empty JSON string", IsoscelesTriangle.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
Set<Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!IsoscelesTriangle.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `IsoscelesTriangle` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `IsoscelesTriangle` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : IsoscelesTriangle.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("shapeType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString()));
}
@@ -216,9 +217,9 @@ public class IsoscelesTriangle {
@Override
public IsoscelesTriangle read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();

View File

@@ -35,6 +35,7 @@ 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;
@@ -54,6 +55,7 @@ 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;
@@ -70,9 +72,9 @@ public class Mammal extends AbstractOpenApiSchema {
return null; // this class only serializes 'Mammal' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Pig> adapterPig = gson.getDelegateAdapter(this, TypeToken.get(Pig.class));
final TypeAdapter<Whale> adapterWhale = gson.getDelegateAdapter(this, TypeToken.get(Whale.class));
final TypeAdapter<Zebra> adapterZebra = gson.getDelegateAdapter(this, TypeToken.get(Zebra.class));
final TypeAdapter<Pig> adapterPig = gson.getDelegateAdapter(this, TypeToken.get(Pig.class));
return (TypeAdapter<T>) new TypeAdapter<Mammal>() {
@Override
@@ -82,34 +84,33 @@ public class Mammal extends AbstractOpenApiSchema {
return;
}
// check if the actual instance is of the type `Pig`
if (value.getActualInstance() instanceof Pig) {
JsonObject obj = adapterPig.toJsonTree((Pig)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Whale`
if (value.getActualInstance() instanceof Whale) {
JsonObject obj = adapterWhale.toJsonTree((Whale)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterWhale.toJsonTree((Whale)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `Zebra`
if (value.getActualInstance() instanceof Zebra) {
JsonObject obj = adapterZebra.toJsonTree((Zebra)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterZebra.toJsonTree((Zebra)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `Pig`
if (value.getActualInstance() instanceof Pig) {
JsonElement element = adapterPig.toJsonTree((Pig)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Pig, Whale, Zebra");
}
@Override
public Mammal read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
JsonObject jsonObject = jsonElement.getAsJsonObject();
// use discriminator value for faster oneOf lookup
Mammal newMammal = new Mammal();
@@ -139,52 +140,50 @@ public class Mammal extends AbstractOpenApiSchema {
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize Pig
try {
// validate the JSON object to see if any exception is thrown
Pig.validateJsonObject(jsonObject);
actualAdapter = adapterPig;
match++;
log.log(Level.FINER, "Input data matches schema 'Pig'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Pig'", e);
}
// deserialize Whale
try {
// validate the JSON object to see if any exception is thrown
Whale.validateJsonObject(jsonObject);
actualAdapter = adapterWhale;
match++;
log.log(Level.FINER, "Input data matches schema 'Whale'");
// validate the JSON object to see if any exception is thrown
Whale.validateJsonElement(jsonElement);
actualAdapter = adapterWhale;
match++;
log.log(Level.FINER, "Input data matches schema 'Whale'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Whale failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Whale'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Whale failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Whale'", e);
}
// deserialize Zebra
try {
// validate the JSON object to see if any exception is thrown
Zebra.validateJsonObject(jsonObject);
actualAdapter = adapterZebra;
match++;
log.log(Level.FINER, "Input data matches schema 'Zebra'");
// validate the JSON object to see if any exception is thrown
Zebra.validateJsonElement(jsonElement);
actualAdapter = adapterZebra;
match++;
log.log(Level.FINER, "Input data matches schema 'Zebra'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Zebra failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Zebra'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Zebra failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Zebra'", e);
}
// deserialize Pig
try {
// validate the JSON object to see if any exception is thrown
Pig.validateJsonElement(jsonElement);
actualAdapter = adapterPig;
match++;
log.log(Level.FINER, "Input data matches schema 'Pig'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Pig'", e);
}
if (match == 1) {
Mammal ret = new Mammal();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Mammal: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for Mammal: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -213,9 +212,9 @@ public class Mammal extends AbstractOpenApiSchema {
}
static {
schemas.put("Pig", Pig.class);
schemas.put("Whale", Whale.class);
schemas.put("Zebra", Zebra.class);
schemas.put("Pig", Pig.class);
}
@Override
@@ -233,11 +232,6 @@ public class Mammal extends AbstractOpenApiSchema {
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof Pig) {
super.setActualInstance(instance);
return;
}
if (instance instanceof Whale) {
super.setActualInstance(instance);
return;
@@ -248,6 +242,11 @@ public class Mammal extends AbstractOpenApiSchema {
return;
}
if (instance instanceof Pig) {
super.setActualInstance(instance);
return;
}
throw new RuntimeException("Invalid instance type. Must be Pig, Whale, Zebra");
}
@@ -262,17 +261,6 @@ public class Mammal extends AbstractOpenApiSchema {
return super.getActualInstance();
}
/**
* Get the actual instance of `Pig`. If the actual instance is not `Pig`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Pig`
* @throws ClassCastException if the instance is not `Pig`
*/
public Pig getPig() throws ClassCastException {
return (Pig)super.getActualInstance();
}
/**
* Get the actual instance of `Whale`. If the actual instance is not `Whale`,
* the ClassCastException will be thrown.
@@ -283,7 +271,6 @@ public class Mammal extends AbstractOpenApiSchema {
public Whale getWhale() throws ClassCastException {
return (Whale)super.getActualInstance();
}
/**
* Get the actual instance of `Zebra`. If the actual instance is not `Zebra`,
* the ClassCastException will be thrown.
@@ -294,29 +281,30 @@ public class Mammal extends AbstractOpenApiSchema {
public Zebra getZebra() throws ClassCastException {
return (Zebra)super.getActualInstance();
}
/**
* Get the actual instance of `Pig`. If the actual instance is not `Pig`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Pig`
* @throws ClassCastException if the instance is not `Pig`
*/
public Pig getPig() throws ClassCastException {
return (Pig)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Mammal
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Mammal
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with Pig
try {
Pig.validateJsonObject(jsonObj);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Whale
try {
Whale.validateJsonObject(jsonObj);
Whale.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Whale failed with `%s`.", e.getMessage()));
@@ -324,14 +312,22 @@ public class Mammal extends AbstractOpenApiSchema {
}
// validate the json string with Zebra
try {
Zebra.validateJsonObject(jsonObj);
Zebra.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Zebra failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Pig
try {
Pig.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Pig failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Mammal with oneOf schemas: Pig, Whale, Zebra. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for Mammal with oneOf schemas: Pig, Whale, Zebra. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -343,17 +343,18 @@ public class MapTest {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to MapTest
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to MapTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!MapTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!MapTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in MapTest is not found in the empty JSON string", MapTest.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@@ -393,8 +394,9 @@ public class MapTest {
@Override
public MapTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
MapTest instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -247,17 +247,18 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to MixedPropertiesAndAdditionalPropertiesClass
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to MixedPropertiesAndAdditionalPropertiesClass
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in MixedPropertiesAndAdditionalPropertiesClass is not found in the empty JSON string", MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString()));
}
@@ -300,8 +301,9 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
@Override
public MixedPropertiesAndAdditionalPropertiesClass read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
MixedPropertiesAndAdditionalPropertiesClass instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -206,17 +206,18 @@ public class Model200Response {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Model200Response
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Model200Response
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Model200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Model200Response.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Model200Response is not found in the empty JSON string", Model200Response.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("class") != null && !jsonObj.get("class").isJsonNull()) && !jsonObj.get("class").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `class` to be a primitive type in the JSON string but got `%s`", jsonObj.get("class").toString()));
}
@@ -259,8 +260,9 @@ public class Model200Response {
@Override
public Model200Response read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Model200Response instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -234,17 +234,18 @@ public class ModelApiResponse {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelApiResponse
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ModelApiResponse
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ModelApiResponse.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString()));
}
@@ -290,8 +291,9 @@ public class ModelApiResponse {
@Override
public ModelApiResponse read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ModelApiResponse instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -178,17 +178,18 @@ public class ModelFile {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelFile
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ModelFile
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ModelFile.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ModelFile.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelFile is not found in the empty JSON string", ModelFile.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("sourceURI") != null && !jsonObj.get("sourceURI").isJsonNull()) && !jsonObj.get("sourceURI").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `sourceURI` to be a primitive type in the JSON string but got `%s`", jsonObj.get("sourceURI").toString()));
}
@@ -231,8 +232,9 @@ public class ModelFile {
@Override
public ModelFile read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ModelFile instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -178,17 +178,18 @@ public class ModelList {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelList
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ModelList
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ModelList.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ModelList.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelList is not found in the empty JSON string", ModelList.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("123-list") != null && !jsonObj.get("123-list").isJsonNull()) && !jsonObj.get("123-list").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `123-list` to be a primitive type in the JSON string but got `%s`", jsonObj.get("123-list").toString()));
}
@@ -231,8 +232,9 @@ public class ModelList {
@Override
public ModelList read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ModelList instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -178,17 +178,18 @@ public class ModelReturn {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelReturn
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ModelReturn
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ModelReturn.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ModelReturn.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelReturn is not found in the empty JSON string", ModelReturn.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@@ -228,8 +229,9 @@ public class ModelReturn {
@Override
public ModelReturn read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ModelReturn instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -255,24 +255,25 @@ public class Name {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Name
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Name
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Name.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Name.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Name is not found in the empty JSON string", Name.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Name.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("property") != null && !jsonObj.get("property").isJsonNull()) && !jsonObj.get("property").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `property` to be a primitive type in the JSON string but got `%s`", jsonObj.get("property").toString()));
}
@@ -315,8 +316,9 @@ public class Name {
@Override
public Name read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Name instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -507,25 +507,26 @@ public class NullableClass {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to NullableClass
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to NullableClass
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!NullableClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!NullableClass.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in NullableClass is not found in the empty JSON string", NullableClass.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
Set<Entry<String, JsonElement>> entries = jsonElement.getAsJsonObject().entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!NullableClass.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `NullableClass` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `NullableClass` properties. JSON: %s", entry.getKey(), jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("string_prop") != null && !jsonObj.get("string_prop").isJsonNull()) && !jsonObj.get("string_prop").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `string_prop` to be a primitive type in the JSON string but got `%s`", jsonObj.get("string_prop").toString()));
}
@@ -563,9 +564,9 @@ public class NullableClass {
@Override
public NullableClass read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
return thisAdapter.fromJsonTree(jsonElement);
}
}.nullSafe();

View File

@@ -34,6 +34,7 @@ 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;
@@ -53,6 +54,7 @@ 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;
@@ -69,8 +71,8 @@ public class NullableShape extends AbstractOpenApiSchema {
return null; // this class only serializes 'NullableShape' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Quadrilateral> adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class));
final TypeAdapter<Triangle> adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class));
final TypeAdapter<Quadrilateral> adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class));
return (TypeAdapter<T>) new TypeAdapter<NullableShape>() {
@Override
@@ -80,27 +82,27 @@ public class NullableShape extends AbstractOpenApiSchema {
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Triangle`
if (value.getActualInstance() instanceof Triangle) {
JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterTriangle.toJsonTree((Triangle)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonElement element = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle");
}
@Override
public NullableShape read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
JsonObject jsonObject = jsonElement.getAsJsonObject();
// use discriminator value for faster oneOf lookup
NullableShape newNullableShape = new NullableShape();
@@ -126,39 +128,38 @@ public class NullableShape extends AbstractOpenApiSchema {
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize Quadrilateral
try {
// validate the JSON object to see if any exception is thrown
Quadrilateral.validateJsonObject(jsonObject);
actualAdapter = adapterQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'Quadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e);
}
// deserialize Triangle
try {
// validate the JSON object to see if any exception is thrown
Triangle.validateJsonObject(jsonObject);
actualAdapter = adapterTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'Triangle'");
// validate the JSON object to see if any exception is thrown
Triangle.validateJsonElement(jsonElement);
actualAdapter = adapterTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'Triangle'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Triangle'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Triangle'", e);
}
// deserialize Quadrilateral
try {
// validate the JSON object to see if any exception is thrown
Quadrilateral.validateJsonElement(jsonElement);
actualAdapter = adapterQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'Quadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e);
}
if (match == 1) {
NullableShape ret = new NullableShape();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for NullableShape: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for NullableShape: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -182,8 +183,8 @@ public class NullableShape extends AbstractOpenApiSchema {
}
static {
schemas.put("Quadrilateral", Quadrilateral.class);
schemas.put("Triangle", Triangle.class);
schemas.put("Quadrilateral", Quadrilateral.class);
}
@Override
@@ -206,12 +207,12 @@ public class NullableShape extends AbstractOpenApiSchema {
return;
}
if (instance instanceof Quadrilateral) {
if (instance instanceof Triangle) {
super.setActualInstance(instance);
return;
}
if (instance instanceof Triangle) {
if (instance instanceof Quadrilateral) {
super.setActualInstance(instance);
return;
}
@@ -230,6 +231,16 @@ public class NullableShape extends AbstractOpenApiSchema {
return super.getActualInstance();
}
/**
* Get the actual instance of `Triangle`. If the actual instance is not `Triangle`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Triangle`
* @throws ClassCastException if the instance is not `Triangle`
*/
public Triangle getTriangle() throws ClassCastException {
return (Triangle)super.getActualInstance();
}
/**
* Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`,
* the ClassCastException will be thrown.
@@ -241,46 +252,34 @@ public class NullableShape extends AbstractOpenApiSchema {
return (Quadrilateral)super.getActualInstance();
}
/**
* Get the actual instance of `Triangle`. If the actual instance is not `Triangle`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Triangle`
* @throws ClassCastException if the instance is not `Triangle`
*/
public Triangle getTriangle() throws ClassCastException {
return (Triangle)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to NullableShape
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to NullableShape
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with Quadrilateral
try {
Quadrilateral.validateJsonObject(jsonObj);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Triangle
try {
Triangle.validateJsonObject(jsonObj);
Triangle.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Quadrilateral
try {
Quadrilateral.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for NullableShape with oneOf schemas: Quadrilateral, Triangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for NullableShape with oneOf schemas: Quadrilateral, Triangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -179,17 +179,18 @@ public class NumberOnly {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to NumberOnly
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to NumberOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!NumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!NumberOnly.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in NumberOnly is not found in the empty JSON string", NumberOnly.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@@ -229,8 +230,9 @@ public class NumberOnly {
@Override
public NumberOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
NumberOnly instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -289,23 +289,24 @@ public class ObjectWithDeprecatedFields {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ObjectWithDeprecatedFields
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ObjectWithDeprecatedFields
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ObjectWithDeprecatedFields.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ObjectWithDeprecatedFields.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ObjectWithDeprecatedFields is not found in the empty JSON string", ObjectWithDeprecatedFields.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("uuid") != null && !jsonObj.get("uuid").isJsonNull()) && !jsonObj.get("uuid").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `uuid` to be a primitive type in the JSON string but got `%s`", jsonObj.get("uuid").toString()));
}
// validate the optional field `deprecatedRef`
if (jsonObj.get("deprecatedRef") != null && !jsonObj.get("deprecatedRef").isJsonNull()) {
DeprecatedObject.validateJsonObject(jsonObj.getAsJsonObject("deprecatedRef"));
DeprecatedObject.validateJsonElement(jsonObj.get("deprecatedRef"));
}
// ensure the optional json data is an array if present
if (jsonObj.get("bars") != null && !jsonObj.get("bars").isJsonArray()) {
@@ -350,8 +351,9 @@ public class ObjectWithDeprecatedFields {
@Override
public ObjectWithDeprecatedFields read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ObjectWithDeprecatedFields instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -368,17 +368,18 @@ public class Order {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Order
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Order
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Order.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString()));
}
@@ -421,8 +422,9 @@ public class Order {
@Override
public Order read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Order instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -235,17 +235,18 @@ public class OuterComposite {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to OuterComposite
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to OuterComposite
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!OuterComposite.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!OuterComposite.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in OuterComposite is not found in the empty JSON string", OuterComposite.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("my_string") != null && !jsonObj.get("my_string").isJsonNull()) && !jsonObj.get("my_string").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `my_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("my_string").toString()));
}
@@ -288,8 +289,9 @@ public class OuterComposite {
@Override
public OuterComposite read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
OuterComposite instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -154,22 +154,22 @@ public class ParentPet extends GrandparentAnimal {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ParentPet
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ParentPet
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ParentPet.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ParentPet.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ParentPet is not found in the empty JSON string", ParentPet.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : ParentPet.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
}
@@ -211,8 +211,9 @@ public class ParentPet extends GrandparentAnimal {
@Override
public ParentPet read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ParentPet instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -389,27 +389,28 @@ public class Pet {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Pet
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Pet
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Pet.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Pet.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `category`
if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) {
Category.validateJsonObject(jsonObj.getAsJsonObject("category"));
Category.validateJsonElement(jsonObj.get("category"));
}
if (!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()));
@@ -430,7 +431,7 @@ public class Pet {
// validate the optional field `tags` (array)
for (int i = 0; i < jsonArraytags.size(); i++) {
Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject());
Tag.validateJsonElement(jsonArraytags.get(i));
};
}
}
@@ -476,8 +477,9 @@ public class Pet {
@Override
public Pet read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Pet instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -390,27 +390,28 @@ public class PetWithRequiredTags {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to PetWithRequiredTags
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to PetWithRequiredTags
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!PetWithRequiredTags.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!PetWithRequiredTags.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in PetWithRequiredTags is not found in the empty JSON string", PetWithRequiredTags.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : PetWithRequiredTags.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
// validate the optional field `category`
if (jsonObj.get("category") != null && !jsonObj.get("category").isJsonNull()) {
Category.validateJsonObject(jsonObj.getAsJsonObject("category"));
Category.validateJsonElement(jsonObj.get("category"));
}
if (!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()));
@@ -429,7 +430,7 @@ public class PetWithRequiredTags {
JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags");
// validate the required field `tags` (array)
for (int i = 0; i < jsonArraytags.size(); i++) {
Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject());
Tag.validateJsonElement(jsonArraytags.get(i));
};
if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString()));
@@ -473,8 +474,9 @@ public class PetWithRequiredTags {
@Override
public PetWithRequiredTags read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
PetWithRequiredTags instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -34,6 +34,7 @@ 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;
@@ -53,6 +54,7 @@ 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;
@@ -82,25 +84,25 @@ public class Pig extends AbstractOpenApiSchema {
// check if the actual instance is of the type `BasquePig`
if (value.getActualInstance() instanceof BasquePig) {
JsonObject obj = adapterBasquePig.toJsonTree((BasquePig)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterBasquePig.toJsonTree((BasquePig)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `DanishPig`
if (value.getActualInstance() instanceof DanishPig) {
JsonObject obj = adapterDanishPig.toJsonTree((DanishPig)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterDanishPig.toJsonTree((DanishPig)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: BasquePig, DanishPig");
}
@Override
public Pig read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
JsonObject jsonObject = jsonElement.getAsJsonObject();
// use discriminator value for faster oneOf lookup
Pig newPig = new Pig();
@@ -128,37 +130,36 @@ public class Pig extends AbstractOpenApiSchema {
// deserialize BasquePig
try {
// validate the JSON object to see if any exception is thrown
BasquePig.validateJsonObject(jsonObject);
actualAdapter = adapterBasquePig;
match++;
log.log(Level.FINER, "Input data matches schema 'BasquePig'");
// validate the JSON object to see if any exception is thrown
BasquePig.validateJsonElement(jsonElement);
actualAdapter = adapterBasquePig;
match++;
log.log(Level.FINER, "Input data matches schema 'BasquePig'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for BasquePig failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'BasquePig'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for BasquePig failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'BasquePig'", e);
}
// deserialize DanishPig
try {
// validate the JSON object to see if any exception is thrown
DanishPig.validateJsonObject(jsonObject);
actualAdapter = adapterDanishPig;
match++;
log.log(Level.FINER, "Input data matches schema 'DanishPig'");
// validate the JSON object to see if any exception is thrown
DanishPig.validateJsonElement(jsonElement);
actualAdapter = adapterDanishPig;
match++;
log.log(Level.FINER, "Input data matches schema 'DanishPig'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for DanishPig failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'DanishPig'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for DanishPig failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'DanishPig'", e);
}
if (match == 1) {
Pig ret = new Pig();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Pig: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for Pig: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -235,7 +236,6 @@ public class Pig extends AbstractOpenApiSchema {
public BasquePig getBasquePig() throws ClassCastException {
return (BasquePig)super.getActualInstance();
}
/**
* Get the actual instance of `DanishPig`. If the actual instance is not `DanishPig`,
* the ClassCastException will be thrown.
@@ -247,20 +247,19 @@ public class Pig extends AbstractOpenApiSchema {
return (DanishPig)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Pig
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Pig
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with BasquePig
try {
BasquePig.validateJsonObject(jsonObj);
BasquePig.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for BasquePig failed with `%s`.", e.getMessage()));
@@ -268,14 +267,14 @@ public class Pig extends AbstractOpenApiSchema {
}
// validate the json string with DanishPig
try {
DanishPig.validateJsonObject(jsonObj);
DanishPig.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for DanishPig failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -34,6 +34,7 @@ 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;
@@ -53,6 +54,7 @@ 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;
@@ -69,8 +71,8 @@ public class Quadrilateral extends AbstractOpenApiSchema {
return null; // this class only serializes 'Quadrilateral' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ComplexQuadrilateral> adapterComplexQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(ComplexQuadrilateral.class));
final TypeAdapter<SimpleQuadrilateral> adapterSimpleQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(SimpleQuadrilateral.class));
final TypeAdapter<ComplexQuadrilateral> adapterComplexQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(ComplexQuadrilateral.class));
return (TypeAdapter<T>) new TypeAdapter<Quadrilateral>() {
@Override
@@ -80,27 +82,27 @@ public class Quadrilateral extends AbstractOpenApiSchema {
return;
}
// check if the actual instance is of the type `ComplexQuadrilateral`
if (value.getActualInstance() instanceof ComplexQuadrilateral) {
JsonObject obj = adapterComplexQuadrilateral.toJsonTree((ComplexQuadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `SimpleQuadrilateral`
if (value.getActualInstance() instanceof SimpleQuadrilateral) {
JsonObject obj = adapterSimpleQuadrilateral.toJsonTree((SimpleQuadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterSimpleQuadrilateral.toJsonTree((SimpleQuadrilateral)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `ComplexQuadrilateral`
if (value.getActualInstance() instanceof ComplexQuadrilateral) {
JsonElement element = adapterComplexQuadrilateral.toJsonTree((ComplexQuadrilateral)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: ComplexQuadrilateral, SimpleQuadrilateral");
}
@Override
public Quadrilateral read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
JsonObject jsonObject = jsonElement.getAsJsonObject();
// use discriminator value for faster oneOf lookup
Quadrilateral newQuadrilateral = new Quadrilateral();
@@ -126,39 +128,38 @@ public class Quadrilateral extends AbstractOpenApiSchema {
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize ComplexQuadrilateral
try {
// validate the JSON object to see if any exception is thrown
ComplexQuadrilateral.validateJsonObject(jsonObject);
actualAdapter = adapterComplexQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'ComplexQuadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for ComplexQuadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'ComplexQuadrilateral'", e);
}
// deserialize SimpleQuadrilateral
try {
// validate the JSON object to see if any exception is thrown
SimpleQuadrilateral.validateJsonObject(jsonObject);
actualAdapter = adapterSimpleQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'SimpleQuadrilateral'");
// validate the JSON object to see if any exception is thrown
SimpleQuadrilateral.validateJsonElement(jsonElement);
actualAdapter = adapterSimpleQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'SimpleQuadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for SimpleQuadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'SimpleQuadrilateral'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for SimpleQuadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'SimpleQuadrilateral'", e);
}
// deserialize ComplexQuadrilateral
try {
// validate the JSON object to see if any exception is thrown
ComplexQuadrilateral.validateJsonElement(jsonElement);
actualAdapter = adapterComplexQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'ComplexQuadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for ComplexQuadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'ComplexQuadrilateral'", e);
}
if (match == 1) {
Quadrilateral ret = new Quadrilateral();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Quadrilateral: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for Quadrilateral: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -182,8 +183,8 @@ public class Quadrilateral extends AbstractOpenApiSchema {
}
static {
schemas.put("ComplexQuadrilateral", ComplexQuadrilateral.class);
schemas.put("SimpleQuadrilateral", SimpleQuadrilateral.class);
schemas.put("ComplexQuadrilateral", ComplexQuadrilateral.class);
}
@Override
@@ -201,12 +202,12 @@ public class Quadrilateral extends AbstractOpenApiSchema {
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof ComplexQuadrilateral) {
if (instance instanceof SimpleQuadrilateral) {
super.setActualInstance(instance);
return;
}
if (instance instanceof SimpleQuadrilateral) {
if (instance instanceof ComplexQuadrilateral) {
super.setActualInstance(instance);
return;
}
@@ -225,6 +226,16 @@ public class Quadrilateral extends AbstractOpenApiSchema {
return super.getActualInstance();
}
/**
* Get the actual instance of `SimpleQuadrilateral`. If the actual instance is not `SimpleQuadrilateral`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `SimpleQuadrilateral`
* @throws ClassCastException if the instance is not `SimpleQuadrilateral`
*/
public SimpleQuadrilateral getSimpleQuadrilateral() throws ClassCastException {
return (SimpleQuadrilateral)super.getActualInstance();
}
/**
* Get the actual instance of `ComplexQuadrilateral`. If the actual instance is not `ComplexQuadrilateral`,
* the ClassCastException will be thrown.
@@ -236,46 +247,34 @@ public class Quadrilateral extends AbstractOpenApiSchema {
return (ComplexQuadrilateral)super.getActualInstance();
}
/**
* Get the actual instance of `SimpleQuadrilateral`. If the actual instance is not `SimpleQuadrilateral`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `SimpleQuadrilateral`
* @throws ClassCastException if the instance is not `SimpleQuadrilateral`
*/
public SimpleQuadrilateral getSimpleQuadrilateral() throws ClassCastException {
return (SimpleQuadrilateral)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Quadrilateral
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Quadrilateral
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with ComplexQuadrilateral
try {
ComplexQuadrilateral.validateJsonObject(jsonObj);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for ComplexQuadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with SimpleQuadrilateral
try {
SimpleQuadrilateral.validateJsonObject(jsonObj);
SimpleQuadrilateral.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for SimpleQuadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with ComplexQuadrilateral
try {
ComplexQuadrilateral.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for ComplexQuadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Quadrilateral with oneOf schemas: ComplexQuadrilateral, SimpleQuadrilateral. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for Quadrilateral with oneOf schemas: ComplexQuadrilateral, SimpleQuadrilateral. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -179,24 +179,25 @@ public class QuadrilateralInterface {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to QuadrilateralInterface
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to QuadrilateralInterface
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!QuadrilateralInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!QuadrilateralInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in QuadrilateralInterface is not found in the empty JSON string", QuadrilateralInterface.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : QuadrilateralInterface.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("quadrilateralType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `quadrilateralType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("quadrilateralType").toString()));
}
@@ -239,8 +240,9 @@ public class QuadrilateralInterface {
@Override
public QuadrilateralInterface read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
QuadrilateralInterface instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -205,17 +205,18 @@ public class ReadOnlyFirst {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ReadOnlyFirst
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ReadOnlyFirst
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ReadOnlyFirst.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ReadOnlyFirst.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ReadOnlyFirst is not found in the empty JSON string", ReadOnlyFirst.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("bar") != null && !jsonObj.get("bar").isJsonNull()) && !jsonObj.get("bar").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `bar` to be a primitive type in the JSON string but got `%s`", jsonObj.get("bar").toString()));
}
@@ -261,8 +262,9 @@ public class ReadOnlyFirst {
@Override
public ReadOnlyFirst read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ReadOnlyFirst instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -0,0 +1,332 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class 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.Arrays;
import java.math.BigDecimal;
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")
public class Scalar extends AbstractOpenApiSchema {
private static final Logger log = Logger.getLogger(Scalar.class.getName());
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Scalar.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Scalar' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<String> adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class));
final TypeAdapter<BigDecimal> adapterBigDecimal = gson.getDelegateAdapter(this, TypeToken.get(BigDecimal.class));
final TypeAdapter<Boolean> adapterBoolean = gson.getDelegateAdapter(this, TypeToken.get(Boolean.class));
return (TypeAdapter<T>) new TypeAdapter<Scalar>() {
@Override
public void write(JsonWriter out, Scalar 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 `BigDecimal`
if (value.getActualInstance() instanceof BigDecimal) {
JsonPrimitive primitive = adapterBigDecimal.toJsonTree((BigDecimal)value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
// check if the actual instance is of the type `Boolean`
if (value.getActualInstance() instanceof Boolean) {
JsonPrimitive primitive = adapterBoolean.toJsonTree((Boolean)value.getActualInstance()).getAsJsonPrimitive();
elementAdapter.write(out, primitive);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: BigDecimal, Boolean, String");
}
@Override
public Scalar read(JsonReader in) throws IOException {
Object deserialized = null;
JsonElement jsonElement = elementAdapter.read(in);
int match = 0;
ArrayList<String> 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 BigDecimal
try {
// validate the JSON object to see if any exception is thrown
if(!jsonElement.getAsJsonPrimitive().isNumber()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Number in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapterBigDecimal;
match++;
log.log(Level.FINER, "Input data matches schema 'BigDecimal'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for BigDecimal failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'BigDecimal'", e);
}
// deserialize Boolean
try {
// validate the JSON object to see if any exception is thrown
if(!jsonElement.getAsJsonPrimitive().isBoolean()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Boolean in the JSON string but got `%s`", jsonElement.toString()));
}
actualAdapter = adapterBoolean;
match++;
log.log(Level.FINER, "Input data matches schema 'Boolean'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Boolean failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Boolean'", e);
}
if (match == 1) {
Scalar ret = new Scalar();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Scalar: %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<String, Class<?>> schemas = new HashMap<String, Class<?>>();
public Scalar() {
super("oneOf", Boolean.FALSE);
}
public Scalar(BigDecimal o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
public Scalar(Boolean o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
public Scalar(String o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
static {
schemas.put("String", String.class);
schemas.put("BigDecimal", BigDecimal.class);
schemas.put("Boolean", Boolean.class);
}
@Override
public Map<String, Class<?>> getSchemas() {
return Scalar.schemas;
}
/**
* Set the instance that matches the oneOf child schema, check
* the instance parameter is valid against the oneOf child schemas:
* BigDecimal, Boolean, String
*
* It could be an instance of the 'oneOf' schemas.
* The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf).
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof String) {
super.setActualInstance(instance);
return;
}
if (instance instanceof BigDecimal) {
super.setActualInstance(instance);
return;
}
if (instance instanceof Boolean) {
super.setActualInstance(instance);
return;
}
throw new RuntimeException("Invalid instance type. Must be BigDecimal, Boolean, String");
}
/**
* Get the actual instance, which can be the following:
* BigDecimal, Boolean, String
*
* @return The actual instance (BigDecimal, Boolean, String)
*/
@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 `BigDecimal`. If the actual instance is not `BigDecimal`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `BigDecimal`
* @throws ClassCastException if the instance is not `BigDecimal`
*/
public BigDecimal getBigDecimal() throws ClassCastException {
return (BigDecimal)super.getActualInstance();
}
/**
* Get the actual instance of `Boolean`. If the actual instance is not `Boolean`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Boolean`
* @throws ClassCastException if the instance is not `Boolean`
*/
public Boolean getBoolean() throws ClassCastException {
return (Boolean)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 Scalar
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> 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 BigDecimal
try {
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()));
}
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for BigDecimal failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Boolean
try {
if(!jsonElement.getAsJsonPrimitive().isBoolean()) {
throw new IllegalArgumentException(String.format("Expected json element to be of type Boolean in the JSON string but got `%s`", jsonElement.toString()));
}
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Boolean failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Scalar with oneOf schemas: BigDecimal, Boolean, 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 Scalar given an JSON string
*
* @param jsonString JSON string
* @return An instance of Scalar
* @throws IOException if the JSON string is invalid with respect to Scalar
*/
public static Scalar fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Scalar.class);
}
/**
* Convert an instance of Scalar to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -208,24 +208,25 @@ public class ScaleneTriangle {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ScaleneTriangle
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ScaleneTriangle
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ScaleneTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ScaleneTriangle.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ScaleneTriangle is not found in the empty JSON string", ScaleneTriangle.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : ScaleneTriangle.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("shapeType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString()));
}
@@ -271,8 +272,9 @@ public class ScaleneTriangle {
@Override
public ScaleneTriangle read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ScaleneTriangle instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -34,6 +34,7 @@ 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;
@@ -53,6 +54,7 @@ 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;
@@ -69,8 +71,8 @@ public class Shape extends AbstractOpenApiSchema {
return null; // this class only serializes 'Shape' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Quadrilateral> adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class));
final TypeAdapter<Triangle> adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class));
final TypeAdapter<Quadrilateral> adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class));
return (TypeAdapter<T>) new TypeAdapter<Shape>() {
@Override
@@ -80,27 +82,27 @@ public class Shape extends AbstractOpenApiSchema {
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Triangle`
if (value.getActualInstance() instanceof Triangle) {
JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterTriangle.toJsonTree((Triangle)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonElement element = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle");
}
@Override
public Shape read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
JsonObject jsonObject = jsonElement.getAsJsonObject();
// use discriminator value for faster oneOf lookup
Shape newShape = new Shape();
@@ -126,39 +128,38 @@ public class Shape extends AbstractOpenApiSchema {
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize Quadrilateral
try {
// validate the JSON object to see if any exception is thrown
Quadrilateral.validateJsonObject(jsonObject);
actualAdapter = adapterQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'Quadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e);
}
// deserialize Triangle
try {
// validate the JSON object to see if any exception is thrown
Triangle.validateJsonObject(jsonObject);
actualAdapter = adapterTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'Triangle'");
// validate the JSON object to see if any exception is thrown
Triangle.validateJsonElement(jsonElement);
actualAdapter = adapterTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'Triangle'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Triangle'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Triangle'", e);
}
// deserialize Quadrilateral
try {
// validate the JSON object to see if any exception is thrown
Quadrilateral.validateJsonElement(jsonElement);
actualAdapter = adapterQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'Quadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e);
}
if (match == 1) {
Shape ret = new Shape();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Shape: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for Shape: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -182,8 +183,8 @@ public class Shape extends AbstractOpenApiSchema {
}
static {
schemas.put("Quadrilateral", Quadrilateral.class);
schemas.put("Triangle", Triangle.class);
schemas.put("Quadrilateral", Quadrilateral.class);
}
@Override
@@ -201,12 +202,12 @@ public class Shape extends AbstractOpenApiSchema {
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof Quadrilateral) {
if (instance instanceof Triangle) {
super.setActualInstance(instance);
return;
}
if (instance instanceof Triangle) {
if (instance instanceof Quadrilateral) {
super.setActualInstance(instance);
return;
}
@@ -225,6 +226,16 @@ public class Shape extends AbstractOpenApiSchema {
return super.getActualInstance();
}
/**
* Get the actual instance of `Triangle`. If the actual instance is not `Triangle`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Triangle`
* @throws ClassCastException if the instance is not `Triangle`
*/
public Triangle getTriangle() throws ClassCastException {
return (Triangle)super.getActualInstance();
}
/**
* Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`,
* the ClassCastException will be thrown.
@@ -236,46 +247,34 @@ public class Shape extends AbstractOpenApiSchema {
return (Quadrilateral)super.getActualInstance();
}
/**
* Get the actual instance of `Triangle`. If the actual instance is not `Triangle`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Triangle`
* @throws ClassCastException if the instance is not `Triangle`
*/
public Triangle getTriangle() throws ClassCastException {
return (Triangle)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Shape
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Shape
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with Quadrilateral
try {
Quadrilateral.validateJsonObject(jsonObj);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Triangle
try {
Triangle.validateJsonObject(jsonObj);
Triangle.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Quadrilateral
try {
Quadrilateral.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Shape with oneOf schemas: Quadrilateral, Triangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for Shape with oneOf schemas: Quadrilateral, Triangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -179,24 +179,25 @@ public class ShapeInterface {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ShapeInterface
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ShapeInterface
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!ShapeInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!ShapeInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in ShapeInterface is not found in the empty JSON string", ShapeInterface.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : ShapeInterface.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("shapeType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString()));
}
@@ -239,8 +240,9 @@ public class ShapeInterface {
@Override
public ShapeInterface read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
ShapeInterface instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -34,6 +34,7 @@ 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;
@@ -53,6 +54,7 @@ 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;
@@ -69,8 +71,8 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
return null; // this class only serializes 'ShapeOrNull' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Quadrilateral> adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class));
final TypeAdapter<Triangle> adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class));
final TypeAdapter<Quadrilateral> adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class));
return (TypeAdapter<T>) new TypeAdapter<ShapeOrNull>() {
@Override
@@ -80,27 +82,27 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
}
// check if the actual instance is of the type `Triangle`
if (value.getActualInstance() instanceof Triangle) {
JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterTriangle.toJsonTree((Triangle)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `Quadrilateral`
if (value.getActualInstance() instanceof Quadrilateral) {
JsonElement element = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle");
}
@Override
public ShapeOrNull read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
JsonObject jsonObject = jsonElement.getAsJsonObject();
// use discriminator value for faster oneOf lookup
ShapeOrNull newShapeOrNull = new ShapeOrNull();
@@ -126,39 +128,38 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize Quadrilateral
try {
// validate the JSON object to see if any exception is thrown
Quadrilateral.validateJsonObject(jsonObject);
actualAdapter = adapterQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'Quadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e);
}
// deserialize Triangle
try {
// validate the JSON object to see if any exception is thrown
Triangle.validateJsonObject(jsonObject);
actualAdapter = adapterTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'Triangle'");
// validate the JSON object to see if any exception is thrown
Triangle.validateJsonElement(jsonElement);
actualAdapter = adapterTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'Triangle'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Triangle'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Triangle'", e);
}
// deserialize Quadrilateral
try {
// validate the JSON object to see if any exception is thrown
Quadrilateral.validateJsonElement(jsonElement);
actualAdapter = adapterQuadrilateral;
match++;
log.log(Level.FINER, "Input data matches schema 'Quadrilateral'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e);
}
if (match == 1) {
ShapeOrNull ret = new ShapeOrNull();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for ShapeOrNull: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for ShapeOrNull: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -182,8 +183,8 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
}
static {
schemas.put("Quadrilateral", Quadrilateral.class);
schemas.put("Triangle", Triangle.class);
schemas.put("Quadrilateral", Quadrilateral.class);
}
@Override
@@ -206,12 +207,12 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
return;
}
if (instance instanceof Quadrilateral) {
if (instance instanceof Triangle) {
super.setActualInstance(instance);
return;
}
if (instance instanceof Triangle) {
if (instance instanceof Quadrilateral) {
super.setActualInstance(instance);
return;
}
@@ -230,6 +231,16 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
return super.getActualInstance();
}
/**
* Get the actual instance of `Triangle`. If the actual instance is not `Triangle`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Triangle`
* @throws ClassCastException if the instance is not `Triangle`
*/
public Triangle getTriangle() throws ClassCastException {
return (Triangle)super.getActualInstance();
}
/**
* Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`,
* the ClassCastException will be thrown.
@@ -241,46 +252,34 @@ public class ShapeOrNull extends AbstractOpenApiSchema {
return (Quadrilateral)super.getActualInstance();
}
/**
* Get the actual instance of `Triangle`. If the actual instance is not `Triangle`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Triangle`
* @throws ClassCastException if the instance is not `Triangle`
*/
public Triangle getTriangle() throws ClassCastException {
return (Triangle)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ShapeOrNull
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to ShapeOrNull
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with Quadrilateral
try {
Quadrilateral.validateJsonObject(jsonObj);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Triangle
try {
Triangle.validateJsonObject(jsonObj);
Triangle.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Triangle failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with Quadrilateral
try {
Quadrilateral.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Quadrilateral failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for ShapeOrNull with oneOf schemas: Quadrilateral, Triangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for ShapeOrNull with oneOf schemas: Quadrilateral, Triangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -208,24 +208,25 @@ public class SimpleQuadrilateral {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to SimpleQuadrilateral
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SimpleQuadrilateral
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!SimpleQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!SimpleQuadrilateral.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in SimpleQuadrilateral is not found in the empty JSON string", SimpleQuadrilateral.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : SimpleQuadrilateral.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("shapeType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `shapeType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("shapeType").toString()));
}
@@ -271,8 +272,9 @@ public class SimpleQuadrilateral {
@Override
public SimpleQuadrilateral read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
SimpleQuadrilateral instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -206,17 +206,18 @@ public class SpecialModelName {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to SpecialModelName
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to SpecialModelName
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!SpecialModelName.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!SpecialModelName.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in SpecialModelName is not found in the empty JSON string", SpecialModelName.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("_special_model.name_") != null && !jsonObj.get("_special_model.name_").isJsonNull()) && !jsonObj.get("_special_model.name_").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `_special_model.name_` to be a primitive type in the JSON string but got `%s`", jsonObj.get("_special_model.name_").toString()));
}
@@ -259,8 +260,9 @@ public class SpecialModelName {
@Override
public SpecialModelName read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
SpecialModelName instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -206,17 +206,18 @@ public class Tag {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Tag
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Tag
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Tag.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Tag is not found in the empty JSON string", Tag.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()));
}
@@ -259,8 +260,9 @@ public class Tag {
@Override
public Tag read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Tag instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -35,6 +35,7 @@ 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;
@@ -54,6 +55,7 @@ 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;
@@ -84,32 +86,31 @@ public class Triangle extends AbstractOpenApiSchema {
// check if the actual instance is of the type `EquilateralTriangle`
if (value.getActualInstance() instanceof EquilateralTriangle) {
JsonObject obj = adapterEquilateralTriangle.toJsonTree((EquilateralTriangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterEquilateralTriangle.toJsonTree((EquilateralTriangle)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `IsoscelesTriangle`
if (value.getActualInstance() instanceof IsoscelesTriangle) {
JsonObject obj = adapterIsoscelesTriangle.toJsonTree((IsoscelesTriangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterIsoscelesTriangle.toJsonTree((IsoscelesTriangle)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `ScaleneTriangle`
if (value.getActualInstance() instanceof ScaleneTriangle) {
JsonObject obj = adapterScaleneTriangle.toJsonTree((ScaleneTriangle)value.getActualInstance()).getAsJsonObject();
elementAdapter.write(out, obj);
return;
JsonElement element = adapterScaleneTriangle.toJsonTree((ScaleneTriangle)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle");
}
@Override
public Triangle read(JsonReader in) throws IOException {
Object deserialized = null;
JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject();
JsonElement jsonElement = elementAdapter.read(in);
JsonObject jsonObject = jsonElement.getAsJsonObject();
// use discriminator value for faster oneOf lookup
Triangle newTriangle = new Triangle();
@@ -141,50 +142,48 @@ public class Triangle extends AbstractOpenApiSchema {
// deserialize EquilateralTriangle
try {
// validate the JSON object to see if any exception is thrown
EquilateralTriangle.validateJsonObject(jsonObject);
actualAdapter = adapterEquilateralTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'EquilateralTriangle'");
// validate the JSON object to see if any exception is thrown
EquilateralTriangle.validateJsonElement(jsonElement);
actualAdapter = adapterEquilateralTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'EquilateralTriangle'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for EquilateralTriangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'EquilateralTriangle'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for EquilateralTriangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'EquilateralTriangle'", e);
}
// deserialize IsoscelesTriangle
try {
// validate the JSON object to see if any exception is thrown
IsoscelesTriangle.validateJsonObject(jsonObject);
actualAdapter = adapterIsoscelesTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'IsoscelesTriangle'");
// validate the JSON object to see if any exception is thrown
IsoscelesTriangle.validateJsonElement(jsonElement);
actualAdapter = adapterIsoscelesTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'IsoscelesTriangle'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for IsoscelesTriangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'IsoscelesTriangle'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for IsoscelesTriangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'IsoscelesTriangle'", e);
}
// deserialize ScaleneTriangle
try {
// validate the JSON object to see if any exception is thrown
ScaleneTriangle.validateJsonObject(jsonObject);
actualAdapter = adapterScaleneTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'ScaleneTriangle'");
// validate the JSON object to see if any exception is thrown
ScaleneTriangle.validateJsonElement(jsonElement);
actualAdapter = adapterScaleneTriangle;
match++;
log.log(Level.FINER, "Input data matches schema 'ScaleneTriangle'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for ScaleneTriangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'ScaleneTriangle'", e);
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for ScaleneTriangle failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'ScaleneTriangle'", e);
}
if (match == 1) {
Triangle ret = new Triangle();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonObject));
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Triangle: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonObject.toString()));
throw new IOException(String.format("Failed deserialization for Triangle: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString()));
}
}.nullSafe();
}
@@ -272,7 +271,6 @@ public class Triangle extends AbstractOpenApiSchema {
public EquilateralTriangle getEquilateralTriangle() throws ClassCastException {
return (EquilateralTriangle)super.getActualInstance();
}
/**
* Get the actual instance of `IsoscelesTriangle`. If the actual instance is not `IsoscelesTriangle`,
* the ClassCastException will be thrown.
@@ -283,7 +281,6 @@ public class Triangle extends AbstractOpenApiSchema {
public IsoscelesTriangle getIsoscelesTriangle() throws ClassCastException {
return (IsoscelesTriangle)super.getActualInstance();
}
/**
* Get the actual instance of `ScaleneTriangle`. If the actual instance is not `ScaleneTriangle`,
* the ClassCastException will be thrown.
@@ -295,20 +292,19 @@ public class Triangle extends AbstractOpenApiSchema {
return (ScaleneTriangle)super.getActualInstance();
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Triangle
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Triangle
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with EquilateralTriangle
try {
EquilateralTriangle.validateJsonObject(jsonObj);
EquilateralTriangle.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for EquilateralTriangle failed with `%s`.", e.getMessage()));
@@ -316,7 +312,7 @@ public class Triangle extends AbstractOpenApiSchema {
}
// validate the json string with IsoscelesTriangle
try {
IsoscelesTriangle.validateJsonObject(jsonObj);
IsoscelesTriangle.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for IsoscelesTriangle failed with `%s`.", e.getMessage()));
@@ -324,14 +320,14 @@ public class Triangle extends AbstractOpenApiSchema {
}
// validate the json string with ScaleneTriangle
try {
ScaleneTriangle.validateJsonObject(jsonObj);
ScaleneTriangle.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for ScaleneTriangle failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Triangle with oneOf schemas: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonObj.toString()));
throw new IOException(String.format("The JSON string is invalid for Triangle with oneOf schemas: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString()));
}
}

View File

@@ -179,24 +179,25 @@ public class TriangleInterface {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to TriangleInterface
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to TriangleInterface
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!TriangleInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!TriangleInterface.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in TriangleInterface is not found in the empty JSON string", TriangleInterface.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : TriangleInterface.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("triangleType").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `triangleType` to be a primitive type in the JSON string but got `%s`", jsonObj.get("triangleType").toString()));
}
@@ -239,8 +240,9 @@ public class TriangleInterface {
@Override
public TriangleInterface read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
TriangleInterface instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -498,17 +498,18 @@ public class User {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to User
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to User
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!User.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in User is not found in the empty JSON string", User.openapiRequiredFields.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("username") != null && !jsonObj.get("username").isJsonNull()) && !jsonObj.get("username").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `username` to be a primitive type in the JSON string but got `%s`", jsonObj.get("username").toString()));
}
@@ -566,8 +567,9 @@ public class User {
@Override
public User read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
User instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -0,0 +1,295 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class 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.Arrays;
import org.openapitools.client.model.Scalar;
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")
public class Value extends AbstractOpenApiSchema {
private static final Logger log = Logger.getLogger(Value.class.getName());
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Value.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Value' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Scalar> adapterScalar = gson.getDelegateAdapter(this, TypeToken.get(Scalar.class));
final Type typeInstance = new TypeToken<List<Scalar>>(){}.getType();
final TypeAdapter<List<Scalar>> adapterScalarList = (TypeAdapter<List<Scalar>>) gson.getDelegateAdapter(this, TypeToken.get(typeInstance));
return (TypeAdapter<T>) new TypeAdapter<Value>() {
@Override
public void write(JsonWriter out, Value value) throws IOException {
if (value == null || value.getActualInstance() == null) {
elementAdapter.write(out, null);
return;
}
// check if the actual instance is of the type `Scalar`
if (value.getActualInstance() instanceof Scalar) {
JsonElement element = adapterScalar.toJsonTree((Scalar)value.getActualInstance());
elementAdapter.write(out, element);
return;
}
// check if the actual instance is of the type `List<Scalar>`
if (value.getActualInstance() instanceof List<?>) {
List<?> list = (List<?>) value.getActualInstance();
if(list.get(0) instanceof Scalar) {
JsonArray array = adapterScalarList.toJsonTree((List<Scalar>)value.getActualInstance()).getAsJsonArray();
elementAdapter.write(out, array);
return;
}
}
throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: List<Scalar>, Scalar");
}
@Override
public Value read(JsonReader in) throws IOException {
Object deserialized = null;
JsonElement jsonElement = elementAdapter.read(in);
int match = 0;
ArrayList<String> errorMessages = new ArrayList<>();
TypeAdapter actualAdapter = elementAdapter;
// deserialize Scalar
try {
// validate the JSON object to see if any exception is thrown
Scalar.validateJsonElement(jsonElement);
actualAdapter = adapterScalar;
match++;
log.log(Level.FINER, "Input data matches schema 'Scalar'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for Scalar failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'Scalar'", e);
}
// deserialize List<Scalar>
try {
// validate the JSON object to see if any exception is thrown
if (!jsonElement.isJsonArray()) {
throw new IllegalArgumentException(String.format("Expected json element to be a array type in the JSON string but got `%s`", jsonElement.toString()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
Scalar.validateJsonElement(element);
}
actualAdapter = adapterScalarList;
match++;
log.log(Level.FINER, "Input data matches schema 'List<Scalar>'");
} catch (Exception e) {
// deserialization failed, continue
errorMessages.add(String.format("Deserialization for List<Scalar> failed with `%s`.", e.getMessage()));
log.log(Level.FINER, "Input data does not match schema 'List<Scalar>'", e);
}
if (match == 1) {
Value ret = new Value();
ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement));
return ret;
}
throw new IOException(String.format("Failed deserialization for Value: %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<String, Class<?>> schemas = new HashMap<String, Class<?>>();
public Value() {
super("oneOf", Boolean.FALSE);
}
public Value(List<Scalar> o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
public Value(Scalar o) {
super("oneOf", Boolean.FALSE);
setActualInstance(o);
}
static {
schemas.put("Scalar", Scalar.class);
schemas.put("List<Scalar>", List.class);
}
@Override
public Map<String, Class<?>> getSchemas() {
return Value.schemas;
}
/**
* Set the instance that matches the oneOf child schema, check
* the instance parameter is valid against the oneOf child schemas:
* List<Scalar>, Scalar
*
* It could be an instance of the 'oneOf' schemas.
* The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf).
*/
@Override
public void setActualInstance(Object instance) {
if (instance instanceof Scalar) {
super.setActualInstance(instance);
return;
}
if (instance instanceof List<?>) {
List<?> list = (List<?>) instance;
if(list.get(0) instanceof Scalar) {
super.setActualInstance(instance);
return;
}
}
throw new RuntimeException("Invalid instance type. Must be List<Scalar>, Scalar");
}
/**
* Get the actual instance, which can be the following:
* List<Scalar>, Scalar
*
* @return The actual instance (List<Scalar>, Scalar)
*/
@Override
public Object getActualInstance() {
return super.getActualInstance();
}
/**
* Get the actual instance of `Scalar`. If the actual instance is not `Scalar`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `Scalar`
* @throws ClassCastException if the instance is not `Scalar`
*/
public Scalar getScalar() throws ClassCastException {
return (Scalar)super.getActualInstance();
}
/**
* Get the actual instance of `List<Scalar>`. If the actual instance is not `List<Scalar>`,
* the ClassCastException will be thrown.
*
* @return The actual instance of `List<Scalar>`
* @throws ClassCastException if the instance is not `List<Scalar>`
*/
public List<Scalar> getScalarList() throws ClassCastException {
return (List<Scalar>)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 Value
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
// validate oneOf schemas one by one
int validCount = 0;
ArrayList<String> errorMessages = new ArrayList<>();
// validate the json string with Scalar
try {
Scalar.validateJsonElement(jsonElement);
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for Scalar failed with `%s`.", e.getMessage()));
// continue to the next one
}
// validate the json string with List<Scalar>
try {
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()));
}
JsonArray array = jsonElement.getAsJsonArray();
// validate array items
for(JsonElement element : array) {
Scalar.validateJsonElement(element);
}
validCount++;
} catch (Exception e) {
errorMessages.add(String.format("Deserialization for List<Scalar> failed with `%s`.", e.getMessage()));
// continue to the next one
}
if (validCount != 1) {
throw new IOException(String.format("The JSON string is invalid for Value with oneOf schemas: List<Scalar>, Scalar. %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 Value given an JSON string
*
* @param jsonString JSON string
* @return An instance of Value
* @throws IOException if the JSON string is invalid with respect to Value
*/
public static Value fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Value.class);
}
/**
* Convert an instance of Value to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -0,0 +1,325 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import org.openapitools.client.model.Value;
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.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Value object
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public class Variable {
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public static final String SERIALIZED_NAME_VALUE = "value";
@SerializedName(SERIALIZED_NAME_VALUE)
private Value value;
public Variable() {
}
public Variable name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@javax.annotation.Nonnull
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Variable value(Value value) {
this.value = value;
return this;
}
/**
* Get value
* @return value
**/
@javax.annotation.Nonnull
public Value getValue() {
return value;
}
public void setValue(Value value) {
this.value = value;
}
/**
* A container for additional, undeclared properties.
* This is a holder for any undeclared properties as specified with
* the 'additionalProperties' keyword in the OAS document.
*/
private Map<String, Object> additionalProperties;
/**
* Set the additional (undeclared) property with the specified name and value.
* If the property does not already exist, create it otherwise replace it.
*
* @param key name of the property
* @param value value of the property
* @return the Variable instance itself
*/
public Variable putAdditionalProperty(String key, Object value) {
if (this.additionalProperties == null) {
this.additionalProperties = new HashMap<String, Object>();
}
this.additionalProperties.put(key, value);
return this;
}
/**
* Return the additional (undeclared) property.
*
* @return a map of objects
*/
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
/**
* Return the additional (undeclared) property with the specified name.
*
* @param key name of the property
* @return an object
*/
public Object getAdditionalProperty(String key) {
if (this.additionalProperties == null) {
return null;
}
return this.additionalProperties.get(key);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Variable variable = (Variable) o;
return Objects.equals(this.name, variable.name) &&
Objects.equals(this.value, variable.value)&&
Objects.equals(this.additionalProperties, variable.additionalProperties);
}
@Override
public int hashCode() {
return Objects.hash(name, value, additionalProperties);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Variable {\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" value: ").append(toIndentedString(value)).append("\n");
sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
openapiFields.add("value");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("name");
openapiRequiredFields.add("value");
}
/**
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Variable
*/
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Variable.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Variable is not found in the empty JSON string", Variable.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Variable.openapiRequiredFields) {
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("name").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString()));
}
// validate the required field `value`
Value.validateJsonElement(jsonObj.get("value"));
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Variable.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Variable' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Variable> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Variable.class));
return (TypeAdapter<T>) new TypeAdapter<Variable>() {
@Override
public void write(JsonWriter out, Variable value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
obj.remove("additionalProperties");
// serialize additional properties
if (value.getAdditionalProperties() != null) {
for (Map.Entry<String, Object> 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 {
obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject());
}
}
}
elementAdapter.write(out, obj);
}
@Override
public Variable read(JsonReader in) throws IOException {
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Variable instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> 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 Variable given an JSON string
*
* @param jsonString JSON string
* @return An instance of Variable
* @throws IOException if the JSON string is invalid with respect to Variable
*/
public static Variable fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Variable.class);
}
/**
* Convert an instance of Variable to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -235,24 +235,25 @@ public class Whale {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Whale
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Whale
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Whale.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Whale.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Whale is not found in the empty JSON string", Whale.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Whale.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if (!jsonObj.get("className").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString()));
}
@@ -295,8 +296,9 @@ public class Whale {
@Override
public Whale read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Whale instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -256,24 +256,25 @@ public class Zebra {
}
/**
* Validates the JSON Object and throws an exception if issues found
* Validates the JSON Element and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Zebra
* @param jsonElement JSON Element
* @throws IOException if the JSON Element is invalid with respect to Zebra
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (!Zebra.openapiRequiredFields.isEmpty()) { // has required fields but JSON object is null
public static void validateJsonElement(JsonElement jsonElement) throws IOException {
if (jsonElement == null) {
if (!Zebra.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null
throw new IllegalArgumentException(String.format("The required field(s) %s in Zebra is not found in the empty JSON string", Zebra.openapiRequiredFields.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Zebra.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
if (jsonElement.getAsJsonObject().get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString()));
}
}
JsonObject jsonObj = jsonElement.getAsJsonObject();
if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) {
throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString()));
}
@@ -319,8 +320,9 @@ public class Zebra {
@Override
public Zebra read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
JsonElement jsonElement = elementAdapter.read(in);
validateJsonElement(jsonElement);
JsonObject jsonObj = jsonElement.getAsJsonObject();
// store additional fields in the deserialized instance
Zebra instance = thisAdapter.fromJsonTree(jsonObj);
for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {

View File

@@ -4,11 +4,13 @@ import static org.junit.jupiter.api.Assertions.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
@@ -22,6 +24,7 @@ import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.TimeZone;
import java.util.List;
import okio.ByteString;
import org.junit.jupiter.api.*;
@@ -430,7 +433,7 @@ public class JSONTest {
Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
Mammal o = json.getGson().fromJson(str, Mammal.class);
});
assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}", exception.getMessage());
assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}", exception.getMessage());
}
{
// Try to deserialize empty object. This should fail 'oneOf' because none will match
@@ -439,7 +442,143 @@ public class JSONTest {
Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> {
json.getGson().fromJson(str, Mammal.class);
});
assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {}`.]. JSON: {}`., Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {}`.]. JSON: {}", exception.getMessage());
assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {}`.]. JSON: {}`.]. JSON: {}", exception.getMessage());
}
}
/**
* Validate a oneOf schema can be deserialized into the expected class.
* The oneOf schema contains primitive Types.
*/
@Test
public void testOneOfSchemaWithPrimitives() throws Exception {
{
String str = "{\"name\":\"bool_1\",\"value\":false}";
Variable variable = json.getGson().fromJson(str, Variable.class);
assertEquals(variable.getName(), "bool_1");
assertTrue(variable.getValue().getActualInstance() instanceof Scalar);
Scalar scalar = (Scalar) variable.getValue().getActualInstance();
assertTrue(scalar.getActualInstance() instanceof Boolean);
Boolean value = (Boolean) scalar.getActualInstance();
assertEquals(value, false);
assertEquals(json.getGson().toJson(variable), str);
}
{
String str = "{\"name\":\"string_1\",\"value\":\"string\"}";
Variable variable = json.getGson().fromJson(str, Variable.class);
assertEquals(variable.getName(), "string_1");
assertTrue(variable.getValue().getActualInstance() instanceof Scalar);
Scalar scalar = (Scalar) variable.getValue().getActualInstance();
assertTrue(scalar.getActualInstance() instanceof String);
String value = (String) scalar.getActualInstance();
assertEquals(value, "string");
assertEquals(json.getGson().toJson(variable), str);
}
{
String str = "{\"name\":\"decimal_1\",\"value\":124567890.0987654321}";
Variable variable = json.getGson().fromJson(str, Variable.class);
assertEquals(variable.getName(), "decimal_1");
assertTrue(variable.getValue().getActualInstance() instanceof Scalar);
Scalar scalar = (Scalar) variable.getValue().getActualInstance();
assertTrue(scalar.getActualInstance() instanceof BigDecimal);
BigDecimal value = (BigDecimal) scalar.getActualInstance();
assertEquals(value, new BigDecimal("124567890.0987654321"));
assertEquals(json.getGson().toJson(variable), str);
}
}
/**
* Validate a oneOf schema can be deserialized into the expected class.
* The oneOf schema contains an array with elements of primitive types.
*/
@Test
public void testOneofSchemaWithArrayOfPrimitives() throws Exception {
{
String str = "{\"name\":\"bool_array_1\",\"value\":[false,true,false]}";
Variable variable = json.getGson().fromJson(str, Variable.class);
assertEquals(variable.getName(), "bool_array_1");
assertTrue(variable.getValue().getActualInstance() instanceof List<?>);
List<Scalar> list = (List<Scalar>) variable.getValue().getActualInstance();
Scalar item_0 = list.get(0);
Scalar item_1 = list.get(1);
Scalar item_2 = list.get(2);
assertTrue(item_0.getActualInstance() instanceof Boolean);
assertTrue(item_1.getActualInstance() instanceof Boolean);
assertTrue(item_2.getActualInstance() instanceof Boolean);
Boolean bool_0 = (Boolean) item_0.getActualInstance();
Boolean bool_1 = (Boolean) item_1.getActualInstance();
Boolean bool_2 = (Boolean) item_2.getActualInstance();
assertEquals(bool_0, false);
assertEquals(bool_1, true);
assertEquals(bool_2, false);
assertEquals(json.getGson().toJson(variable), str);
}
{
String str = "{\"name\":\"string_array_1\",\"value\":[\"string_0\",\"string_1\",\"string_2\"]}";
Variable variable = json.getGson().fromJson(str, Variable.class);
assertEquals(variable.getName(), "string_array_1");
assertTrue(variable.getValue().getActualInstance() instanceof List<?>);
List<Scalar> list = (List<Scalar>) variable.getValue().getActualInstance();
Scalar item_0 = list.get(0);
Scalar item_1 = list.get(1);
Scalar item_2 = list.get(2);
assertTrue(item_0.getActualInstance() instanceof String);
assertTrue(item_1.getActualInstance() instanceof String);
assertTrue(item_2.getActualInstance() instanceof String);
String string_0 = (String) item_0.getActualInstance();
String string_1 = (String) item_1.getActualInstance();
String string_2 = (String) item_2.getActualInstance();
assertEquals(string_0, "string_0");
assertEquals(string_1, "string_1");
assertEquals(string_2, "string_2");
assertEquals(json.getGson().toJson(variable), str);
}
{
String str = "{\"name\":\"decimal_array_1\",\"value\":[124567890.0987654321,987654321.123456789,1112222210.2222222211]}";
Variable variable = json.getGson().fromJson(str, Variable.class);
assertEquals(variable.getName(), "decimal_array_1");
assertTrue(variable.getValue().getActualInstance() instanceof List<?>);
List<Scalar> list = (List<Scalar>) variable.getValue().getActualInstance();
Scalar item_0 = list.get(0);
Scalar item_1 = list.get(1);
Scalar item_2 = list.get(2);
assertTrue(item_0.getActualInstance() instanceof BigDecimal);
assertTrue(item_1.getActualInstance() instanceof BigDecimal);
assertTrue(item_2.getActualInstance() instanceof BigDecimal);
BigDecimal decimal_0 = (BigDecimal) item_0.getActualInstance();
BigDecimal decimal_1 = (BigDecimal) item_1.getActualInstance();
BigDecimal decimal_2 = (BigDecimal) item_2.getActualInstance();
assertEquals(decimal_0, new BigDecimal("124567890.0987654321"));
assertEquals(decimal_1, new BigDecimal("987654321.123456789"));
assertEquals(decimal_2, new BigDecimal("1112222210.2222222211"));
assertEquals(json.getGson().toJson(variable), str);
}
}
@@ -547,14 +686,14 @@ public class JSONTest {
/**
* Test validateJsonObject with null object
* Test validateJsonElement with null object
*/
@Test
public void testValidateJsonObject() throws Exception {
JsonObject jsonObject = new JsonObject();
public void testValidateJsonElement() throws Exception {
JsonElement jsonElement = json.getGson().toJsonTree(new JsonObject());
Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> {
Pet.validateJsonObject(jsonObject);
});
Pet.validateJsonElement(jsonElement);
});
assertEquals(exception.getMessage(), "The required field `photoUrls` is not found in the JSON string: {}");
}

View File

@@ -0,0 +1,47 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.api;
import org.openapitools.client.ApiException;
import org.openapitools.client.model.Variable;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* API tests for ValuesApi
*/
@Disabled
public class ValuesApiTest {
private final ValuesApi api = new ValuesApi();
/**
* Get some primitive variable values
*
*
*
* @throws ApiException if the Api call fails
*/
@Test
public void getSomeValuesTest() throws ApiException {
Variable response = api.getSomeValues();
// TODO: test validations
}
}

View File

@@ -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 org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Model tests for Scalar
*/
public class ScalarTest {
private final Scalar model = new Scalar();
/**
* Model tests for Scalar
*/
@Test
public void testScalar() {
// TODO: test Scalar
}
}

View File

@@ -0,0 +1,35 @@
/*
* OpenAPI Petstore
* This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import org.openapitools.client.model.Scalar;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Model tests for Value
*/
public class ValueTest {
private final Value model = new Value();
/**
* Model tests for Value
*/
@Test
public void testValue() {
// TODO: test Value
}
}

View File

@@ -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 org.openapitools.client.model.Value;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
/**
* Model tests for Variable
*/
public class VariableTest {
private final Variable model = new Variable();
/**
* Model tests for Variable
*/
@Test
public void testVariable() {
// TODO: test Variable
}
/**
* Test the property 'name'
*/
@Test
public void nameTest() {
// TODO: test name
}
/**
* Test the property 'value'
*/
@Test
public void valueTest() {
// TODO: test value
}
}