Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Java] add missing nullable judgement when required property is true #18518

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -398,7 +398,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
{{#items.isModel}}
{{#required}}
// ensure the json data is an array
if (!jsonObj.get("{{{baseName}}}").isJsonArray()) {
if (!jsonObj.get("{{{baseName}}}").isJsonArray(){{#isNullable}} && !jsonObj.get("{{baseName}}").isJsonNull(){{/isNullable}}) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the fix and the test.

shall the new condition {{#isNullable}} && !jsonObj.get("{{baseName}}").isJsonNull(){{/isNullable}} be put in its own code block instead of adding to the JSON array type check as the error message right below only mentions expecting the field to be an array?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks for the fix and the test.

shall the new condition {{#isNullable}} && !jsonObj.get("{{baseName}}").isJsonNull(){{/isNullable}} be put in its own code block instead of adding to the JSON array type check as the error message right below only mentions expecting the field to be an array?

Hi, I don't quite understand. It doesn't seem to make sense to bring up the nullable judgment alone, because nullable is just an auxiliary judgment. If we put in its own code block, the nullable judgment is set outside the original judgment. From the code point of view, the logic is the same. If you write a judgment to nullable alone to throw an exception, the whole logic will seem even more strange.

     {{^isNullable}}
      if (jsonObj.get("{{baseName}}").isJsonNull()) {
        // throw exception here 
      }
      {{/isNullable}}
      // we will get an exception in the next judgement if json element is null
      // ensure the json data is an array
      if (!jsonObj.get("{{{baseName}}}").isJsonArray()) {
        throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString()));
      }

Or this is the change you want.

{{#isNullable}} 
if  (!jsonObj.get("{{baseName}}").isJsonNull()) {
  // ensure the json data is an array
        if (!jsonObj.get("{{{baseName}}}").isJsonArray()) {
          throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString()));
        }
}
{{/isNullable}}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok👌

throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString()));
}

Expand Down Expand Up @@ -436,7 +436,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
// ensure the required json array is present
if (jsonObj.get("{{{baseName}}}") == null) {
throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`");
} else if (!jsonObj.get("{{{baseName}}}").isJsonArray()) {
} else if (!jsonObj.get("{{{baseName}}}").isJsonArray(){{#isNullable}} && !jsonObj.get("{{baseName}}").isJsonNull(){{/isNullable}}) {
throw new IllegalArgumentException(String.format("Expected the field `{{{baseName}}}` to be an array in the JSON string but got `%s`", jsonObj.get("{{{baseName}}}").toString()));
}
{{/required}}
Expand All @@ -450,8 +450,14 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
{{/isString}}
{{#isModel}}
{{#required}}
{{#isNullable}}
if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) {
{{/isNullable}}
// validate the required field `{{{baseName}}}`
{{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}"));
{{#isNullable}}
}
{{/isNullable}}
{{/required}}
{{^required}}
// validate the optional field `{{{baseName}}}`
Expand All @@ -462,8 +468,14 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
{{/isModel}}
{{#isEnum}}
{{#required}}
{{#isNullable}}
if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) {
{{/isNullable}}
// validate the required field `{{{baseName}}}`
{{{datatypeWithEnum}}}.validateJsonElement(jsonObj.get("{{{baseName}}}"));
{{#isNullable}}
}
{{/isNullable}}
{{/required}}
{{^required}}
// validate the optional field `{{{baseName}}}`
Expand All @@ -474,8 +486,14 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens
{{/isEnum}}
{{#isEnumRef}}
{{#required}}
{{#isNullable}}
if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) {
{{/isNullable}}
// validate the required field `{{{baseName}}}`
{{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}"));
{{#isNullable}}
}
{{/isNullable}}
{{/required}}
{{^required}}
// validate the optional field `{{{baseName}}}`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2676,4 +2676,31 @@ static private Path newTempFolder() {
throw new RuntimeException(e);
}
}

@Test public void testRequiredAndNullableAreBothTrue() throws IOException {
File output = Files.createTempDirectory("test").toFile();
output.deleteOnExit();

final CodegenConfigurator configurator = new CodegenConfigurator()
.setGeneratorName("java")
.setLibrary(JavaClientCodegen.OKHTTP_GSON)
.setInputSpec("src/test/resources/bugs/issue_18516.yaml")
.setOutputDir(output.getAbsolutePath().replace("\\", "/"));


DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(configurator.toClientOptInput()).generate();
files.forEach(File::deleteOnExit);

validateJavaSourceFiles(files);

Path modelFile = Paths.get(output + "/src/main/java/org/openapitools/client/model/SomeObject.java");
TestUtils.assertFileContains(
modelFile,
"} else if (!jsonObj.get(\"ids\").isJsonArray() && !jsonObj.get(\"ids\").isJsonNull()) {",
"if (!jsonObj.get(\"users\").isJsonArray() && !jsonObj.get(\"users\").isJsonNull()) {",
"if (jsonObj.get(\"user\") != null && !jsonObj.get(\"user\").isJsonNull()) {",
"if (jsonObj.get(\"role\") != null && !jsonObj.get(\"role\").isJsonNull()) {",
"if (jsonObj.get(\"custom\") != null && !jsonObj.get(\"custom\").isJsonNull()) {");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -1382,6 +1382,19 @@ paths:
$ref: '#/components/schemas/Variable'
'400':
description: Invalid Value
/fake/required-nullable-body:
get:
tags:
- fake
summary: fields in the response body, required and nullable are both true
description: ''
responses:
'200':
description: success
content:
application/json:
schema:
$ref: '#/components/schemas/RequiredNullableBody'
servers:
- url: 'http://{server}.swagger.io:{port}/v2'
description: petstore server
Expand Down Expand Up @@ -2748,3 +2761,35 @@ components:
$ref: '#/components/schemas/ArrayOneOf'
anyof_prop:
$ref: '#/components/schemas/ArrayAnyOf'
NullableEnum:
type: string
nullable: true
enum:
- custom
RequiredNullableBody:
allOf:
- $ref: '#/components/schemas/NullableClass'
- type: object
required:
- custom_ref_enum
- custom_enum
- integer_prop
- number_prop
- boolean_prop
- string_prop
- date_prop
- datetime_prop
- array_nullable_prop
- array_and_items_nullable_prop
- array_items_nullable
- object_nullable_prop
- object_and_items_nullable_prop
- object_items_nullable
properties:
custom_ref_enum:
$ref: "#/components/schemas/NullableEnum"
custom_enum:
type: string
nullable: true
enum:
- custom
61 changes: 61 additions & 0 deletions modules/openapi-generator/src/test/resources/bugs/issue_18516.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
openapi: 3.0.3
info:
title: test
description: Test API
version: 1.0.1

paths:
/test:
get:
responses:
200:
description: Valid response
content:
application/json:
schema:
$ref: "#/components/schemas/SomeObject"

components:
schemas:
SomeObject:
type: object
required:
- ids
- users
- user
- role
- custom
properties:
ids:
type: array
nullable: true
items:
type: integer
users:
type: array
nullable: true
items:
type: object
properties:
id:
type: string
user:
type: object
nullable: true
properties:
id:
type: string
role:
type: string
nullable: true
enum:
- admin
- tenant
custom:
$ref: "#/components/schemas/customEnum"
customEnum:
type: string
nullable: true
enum:
- custom

Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti
// ensure the required json array is present
if (jsonObj.get("photoUrls") == null) {
throw new IllegalArgumentException("Expected the field `linkedContent` to be an array in the JSON string but got `null`");
} else if (!jsonObj.get("photoUrls").isJsonArray()) {
} else if (!jsonObj.get("photoUrls").isJsonArray() && !jsonObj.get("photoUrls").isJsonNull()) {
throw new IllegalArgumentException(String.format("Expected the field `photoUrls` to be an array in the JSON string but got `%s`", jsonObj.get("photoUrls").toString()));
}
if (jsonObj.get("tags") != null && !jsonObj.get("tags").isJsonNull()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ docs/NewPet.md
docs/NewPetCategoryInlineAllof.md
docs/NewPetCategoryInlineAllofAllOfCategoryTag.md
docs/NullableClass.md
docs/NullableEnum.md
docs/NullableShape.md
docs/NumberOnly.md
docs/ObjectWithDeprecatedFields.md
Expand All @@ -94,6 +95,7 @@ docs/PropertyNameCollision.md
docs/Quadrilateral.md
docs/QuadrilateralInterface.md
docs/ReadOnlyFirst.md
docs/RequiredNullableBody.md
docs/Scalar.md
docs/ScalarAnyOf.md
docs/ScaleneTriangle.md
Expand Down Expand Up @@ -216,6 +218,7 @@ src/main/java/org/openapitools/client/model/NewPet.java
src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java
src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java
src/main/java/org/openapitools/client/model/NullableClass.java
src/main/java/org/openapitools/client/model/NullableEnum.java
src/main/java/org/openapitools/client/model/NullableShape.java
src/main/java/org/openapitools/client/model/NumberOnly.java
src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java
Expand All @@ -236,6 +239,7 @@ src/main/java/org/openapitools/client/model/PropertyNameCollision.java
src/main/java/org/openapitools/client/model/Quadrilateral.java
src/main/java/org/openapitools/client/model/QuadrilateralInterface.java
src/main/java/org/openapitools/client/model/ReadOnlyFirst.java
src/main/java/org/openapitools/client/model/RequiredNullableBody.java
src/main/java/org/openapitools/client/model/Scalar.java
src/main/java/org/openapitools/client/model/ScalarAnyOf.java
src/main/java/org/openapitools/client/model/ScaleneTriangle.java
Expand Down
3 changes: 3 additions & 0 deletions samples/client/petstore/java/okhttp-gson/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ Class | Method | HTTP request | Description
*FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite |
*FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number |
*FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string |
*FakeApi* | [**fakeRequiredNullableBodyGet**](docs/FakeApi.md#fakeRequiredNullableBodyGet) | **GET** /fake/required-nullable-body | fields in the response body, required and nullable are both true
*FakeApi* | [**fakeUploadRefRequestBodies**](docs/FakeApi.md#fakeUploadRefRequestBodies) | **POST** /fake/pet/{petId}/uploadImage | fake uploads an image with ref request bodies
*FakeApi* | [**getFakeArrayofenums**](docs/FakeApi.md#getFakeArrayofenums) | **GET** /fake/array-of-enums | Array of Enums
*FakeApi* | [**getFakeHealth**](docs/FakeApi.md#getFakeHealth) | **GET** /fake/health | Health check endpoint
Expand Down Expand Up @@ -233,6 +234,7 @@ Class | Method | HTTP request | Description
- [NewPetCategoryInlineAllof](docs/NewPetCategoryInlineAllof.md)
- [NewPetCategoryInlineAllofAllOfCategoryTag](docs/NewPetCategoryInlineAllofAllOfCategoryTag.md)
- [NullableClass](docs/NullableClass.md)
- [NullableEnum](docs/NullableEnum.md)
- [NullableShape](docs/NullableShape.md)
- [NumberOnly](docs/NumberOnly.md)
- [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md)
Expand All @@ -253,6 +255,7 @@ Class | Method | HTTP request | Description
- [Quadrilateral](docs/Quadrilateral.md)
- [QuadrilateralInterface](docs/QuadrilateralInterface.md)
- [ReadOnlyFirst](docs/ReadOnlyFirst.md)
- [RequiredNullableBody](docs/RequiredNullableBody.md)
- [Scalar](docs/Scalar.md)
- [ScalarAnyOf](docs/ScalarAnyOf.md)
- [ScaleneTriangle](docs/ScaleneTriangle.md)
Expand Down
71 changes: 71 additions & 0 deletions samples/client/petstore/java/okhttp-gson/api/openapi.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1479,6 +1479,21 @@ paths:
x-internal: true
x-accepts:
- application/json
/fake/required-nullable-body:
get:
description: ""
responses:
"200":
content:
application/json:
schema:
$ref: '#/components/schemas/RequiredNullableBody'
description: success
summary: "fields in the response body, required and nullable are both true"
tags:
- fake
x-accepts:
- application/json
components:
requestBodies:
upload_body:
Expand Down Expand Up @@ -2778,6 +2793,62 @@ components:
anyof_prop:
$ref: '#/components/schemas/ArrayAnyOf'
type: object
NullableEnum:
enum:
- custom
nullable: true
type: string
RequiredNullableBody:
allOf:
- $ref: '#/components/schemas/NullableClass'
- properties:
custom_ref_enum:
$ref: '#/components/schemas/NullableEnum'
custom_enum:
enum:
- custom
nullable: true
type: string
required:
- array_and_items_nullable_prop
- array_items_nullable
- array_nullable_prop
- boolean_prop
- custom_enum
- custom_ref_enum
- date_prop
- datetime_prop
- integer_prop
- number_prop
- object_and_items_nullable_prop
- object_items_nullable
- object_nullable_prop
- string_prop
type: object
example:
number_prop: 6.027456183070403
datetime_prop: 2000-01-23T04:56:07.000+00:00
custom_ref_enum: custom
boolean_prop: true
string_prop: string_prop
array_nullable_prop:
- "{}"
- "{}"
custom_enum: custom
integer_prop: 0
array_and_items_nullable_prop:
- "{}"
- "{}"
object_items_nullable:
key: "{}"
object_nullable_prop:
key: "{}"
object_and_items_nullable_prop:
key: "{}"
date_prop: 2000-01-23
array_items_nullable:
- "{}"
- "{}"
_foo_get_default_response:
example:
string:
Expand Down
Loading
Loading