diff --git a/bin/configs/java-webclient-nullable-array.yaml b/bin/configs/java-webclient-nullable-array.yaml new file mode 100644 index 00000000000..224f2285208 --- /dev/null +++ b/bin/configs/java-webclient-nullable-array.yaml @@ -0,0 +1,7 @@ +generatorName: java +outputDir: samples/client/petstore/java/webclient-nulable-arrays +library: webclient +inputSpec: modules/openapi-generator/src/test/resources/3_0/schema-with-nullable-arrays.yaml +additionalProperties: + artifactId: petstore-webclient-nullable-arrays + hideGenerationTimestamp: "true" diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index aaa988a6109..a5d05d09cb6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -1219,6 +1219,13 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code model.imports.add("ApiModelProperty"); model.imports.add("ApiModel"); } + + if (openApiNullable) { + if (Boolean.FALSE.equals(property.required) && Boolean.TRUE.equals(property.isNullable)) { + model.imports.add("JsonNullable"); + model.getVendorExtensions().put("x-jackson-optional-nullable-helpers", true); + } + } } @Override diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java index 10e354d6f7f..57ad135e867 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaJerseyServerCodegen.java @@ -126,6 +126,9 @@ public class JavaJerseyServerCodegen extends AbstractJavaJAXRSServerCodegen { supportingFiles.add(new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml") .doNotOverwrite()); supportingFiles.add(new SupportingFile("StringUtil.mustache", (sourceFolder + '/' + apiPackage).replace(".", "/"), "StringUtil.java")); + + // JsonNullable is not implemented for this generator + openApiNullable = false; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache index 9a4c6dd3c90..55dc3717100 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache @@ -278,13 +278,17 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE return false; }{{#hasVars}} {{classname}} {{classVarName}} = ({{classname}}) o; - return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} && {{/-last}}{{/vars}}{{#additionalPropertiesType}}&& Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/additionalPropertiesType}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} {{/useReflectionEqualsHashCode}} - } + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public int hashCode() { @@ -292,9 +296,18 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE return HashCodeBuilder.reflectionHashCode(this); {{/useReflectionEqualsHashCode}} {{^useReflectionEqualsHashCode}} - return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/additionalPropertiesType}}); + return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/additionalPropertiesType}}); {{/useReflectionEqualsHashCode}} - } + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public String toString() { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache index e1350909a53..2db2da784e9 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache @@ -281,13 +281,17 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE return false; }{{#hasVars}} {{classname}} {{classVarName}} = ({{classname}}) o; - return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} && {{/-last}}{{/vars}}{{#additionalPropertiesType}}&& Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/additionalPropertiesType}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} {{/useReflectionEqualsHashCode}} - } + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public int hashCode() { @@ -295,9 +299,18 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE return HashCodeBuilder.reflectionHashCode(this); {{/useReflectionEqualsHashCode}} {{^useReflectionEqualsHashCode}} - return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}, additionalProperties{{/additionalPropertiesType}}); + return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#additionalPropertiesType}}, additionalProperties{{/additionalPropertiesType}}); {{/useReflectionEqualsHashCode}} - } + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public String toString() { diff --git a/modules/openapi-generator/src/main/resources/Java/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/pojo.mustache index 6590b93824d..77d080ccba3 100644 --- a/modules/openapi-generator/src/main/resources/Java/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/pojo.mustache @@ -255,12 +255,16 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE return false; }{{#hasVars}} {{classname}} {{classVarName}} = ({{classname}}) o; - return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} && {{/-last}}{{/vars}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} {{/useReflectionEqualsHashCode}} - } + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public int hashCode() { @@ -268,9 +272,18 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE return HashCodeBuilder.reflectionHashCode(this); {{/useReflectionEqualsHashCode}} {{^useReflectionEqualsHashCode}} - return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); {{/useReflectionEqualsHashCode}} - } + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public String toString() { diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache index 3938d4d289e..de2f292341e 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache @@ -132,16 +132,29 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}}{{^parent}} return false; }{{#hasVars}} {{classname}} {{classVarName}} = ({{classname}}) o; - return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} && {{/-last}}{{/vars}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} - } + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public int hashCode() { - return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); - } + return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} @Override public String toString() { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java index 13b247940f5..abe7aee3411 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaCXFClientCodegenTest.java @@ -276,7 +276,7 @@ public class JavaCXFClientCodegenTest { codegenProperty.isNullable = true; codegen.postProcessModelProperty(codegenModel, codegenProperty); - Assert.assertFalse(codegenModel.imports.contains("JsonNullable")); + Assert.assertTrue(codegenModel.imports.contains("JsonNullable")); Assert.assertFalse(codegenModel.imports.contains("JsonIgnore")); Assert.assertNull(codegenProperty.getVendorExtensions().get("x-is-jackson-optional-nullable")); } diff --git a/modules/openapi-generator/src/test/resources/3_0/schema-with-nullable-arrays.yaml b/modules/openapi-generator/src/test/resources/3_0/schema-with-nullable-arrays.yaml new file mode 100644 index 00000000000..9a94a2e548a --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/schema-with-nullable-arrays.yaml @@ -0,0 +1,43 @@ +openapi: 3.0.0 +info: + title: 'Minimal Example ' + description: byte Array error in equal method + version: v1 +paths: + /nullable-array-test: + get: + summary: '' + description: '' + operationId: '' + parameters: [] + responses: + '200': + description: '' + content: + application/json: + schema: + type: array + items: + "$ref": "#/components/schemas/ByteArrayObject" +components: + schemas: + ByteArrayObject: + type: object + properties: + nullableArray: + type: string + description: byte array. + format: byte + nullable: true + normalArray: + type: string + description: byte array. + format: byte + nullableString: + type: string + nullable: true + stringField: + type: string + intField: + type: number + format: int32 diff --git a/pom.xml b/pom.xml index 63dbee00700..38449ea2435 100644 --- a/pom.xml +++ b/pom.xml @@ -1343,6 +1343,7 @@ samples/client/petstore/java/resttemplate samples/client/petstore/java/resttemplate-withXml samples/client/petstore/java/webclient + samples/client/petstore/java/webclient-nulable-arrays samples/client/petstore/java/vertx samples/client/petstore/java/jersey2-java8-localdatetime samples/client/petstore/java/resteasy diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java index c9e35dd1b5e..a2bc31cdab7 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/EnumTest.java @@ -26,6 +26,7 @@ import org.openapitools.client.model.OuterEnum; import org.openapitools.client.model.OuterEnumDefaultValue; import org.openapitools.client.model.OuterEnumInteger; import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -453,15 +454,28 @@ public class EnumTest { Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && Objects.equals(this.enumInteger, enumTest.enumInteger) && Objects.equals(this.enumNumber, enumTest.enumNumber) && - Objects.equals(this.outerEnum, enumTest.outerEnum) && + equalsNullable(this.outerEnum, enumTest.outerEnum) && Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(enumString, enumStringRequired, enumInteger, enumNumber, outerEnum, outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); + return Objects.hash(enumString, enumStringRequired, enumInteger, enumNumber, hashCodeNullable(outerEnum), outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java index fca0af36793..9ca1ed06b50 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -85,12 +86,25 @@ public class HealthCheckResult { return false; } HealthCheckResult healthCheckResult = (HealthCheckResult) o; - return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage); + return equalsNullable(this.nullableMessage, healthCheckResult.nullableMessage); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); } @Override public int hashCode() { - return Objects.hash(nullableMessage); + return Objects.hash(hashCodeNullable(nullableMessage)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java index 8e58ce2fcea..a0cdc543f9c 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/NullableClass.java @@ -27,6 +27,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; import org.threeten.bp.LocalDate; import org.threeten.bp.OffsetDateTime; import com.fasterxml.jackson.annotation.JsonIgnore; @@ -568,24 +569,37 @@ public class NullableClass extends HashMap { return false; } NullableClass nullableClass = (NullableClass) o; - return Objects.equals(this.integerProp, nullableClass.integerProp) && - Objects.equals(this.numberProp, nullableClass.numberProp) && - Objects.equals(this.booleanProp, nullableClass.booleanProp) && - Objects.equals(this.stringProp, nullableClass.stringProp) && - Objects.equals(this.dateProp, nullableClass.dateProp) && - Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && - Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && - Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && + return equalsNullable(this.integerProp, nullableClass.integerProp) && + equalsNullable(this.numberProp, nullableClass.numberProp) && + equalsNullable(this.booleanProp, nullableClass.booleanProp) && + equalsNullable(this.stringProp, nullableClass.stringProp) && + equalsNullable(this.dateProp, nullableClass.dateProp) && + equalsNullable(this.datetimeProp, nullableClass.datetimeProp) && + equalsNullable(this.arrayNullableProp, nullableClass.arrayNullableProp) && + equalsNullable(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && - Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && - Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && + equalsNullable(this.objectNullableProp, nullableClass.objectNullableProp) && + equalsNullable(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable) && super.equals(o); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, super.hashCode()); + return Objects.hash(hashCodeNullable(integerProp), hashCodeNullable(numberProp), hashCodeNullable(booleanProp), hashCodeNullable(stringProp), hashCodeNullable(dateProp), hashCodeNullable(datetimeProp), hashCodeNullable(arrayNullableProp), hashCodeNullable(arrayAndItemsNullableProp), arrayItemsNullable, hashCodeNullable(objectNullableProp), hashCodeNullable(objectAndItemsNullableProp), objectItemsNullable, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/client/petstore/java/webclient-nulable-arrays/.gitignore b/samples/client/petstore/java/webclient-nulable-arrays/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator-ignore b/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator/FILES b/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator/FILES new file mode 100644 index 00000000000..eaed93f7b08 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator/FILES @@ -0,0 +1,29 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/ByteArrayObject.md +docs/DefaultApi.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/JavaTimeFormatter.java +src/main/java/org/openapitools/client/RFC3339DateFormat.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/DefaultApi.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 +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/model/ByteArrayObject.java diff --git a/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator/VERSION b/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator/VERSION new file mode 100644 index 00000000000..862529f8cac --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.2.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/webclient-nulable-arrays/.travis.yml b/samples/client/petstore/java/webclient-nulable-arrays/.travis.yml new file mode 100644 index 00000000000..1b6741c083c --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/client/petstore/java/webclient-nulable-arrays/README.md b/samples/client/petstore/java/webclient-nulable-arrays/README.md new file mode 100644 index 00000000000..c74918e7d1c --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/README.md @@ -0,0 +1,128 @@ +# petstore-webclient-nullable-arrays + +Minimal Example + +- API version: v1 + +byte Array error in equal method + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.8+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + petstore-webclient-nullable-arrays + v1 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "org.openapitools:petstore-webclient-nullable-arrays:v1" +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/petstore-webclient-nullable-arrays-v1.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import org.openapitools.client.*; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.DefaultApi; + +public class DefaultApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + List result = apiInstance.nullableArrayTestGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#nullableArrayTestGet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**nullableArrayTestGet**](docs/DefaultApi.md#nullableArrayTestGet) | **GET** /nullable-array-test | + + +## Documentation for Models + + - [ByteArrayObject](docs/ByteArrayObject.md) + + +## Documentation for Authorization + +All endpoints do not require authorization. +Authentication schemes defined for the API: + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + + + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/api/openapi.yaml b/samples/client/petstore/java/webclient-nulable-arrays/api/openapi.yaml new file mode 100644 index 00000000000..2619b457689 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/api/openapi.yaml @@ -0,0 +1,49 @@ +openapi: 3.0.0 +info: + description: byte Array error in equal method + title: 'Minimal Example ' + version: v1 +servers: +- url: / +paths: + /nullable-array-test: + get: + parameters: [] + responses: + "200": + content: + application/json: + schema: + items: + $ref: '#/components/schemas/ByteArrayObject' + type: array + x-accepts: application/json +components: + schemas: + ByteArrayObject: + example: + nullableArray: nullableArray + nullableString: nullableString + normalArray: normalArray + stringField: stringField + intField: 0.8008281904610115 + properties: + nullableArray: + description: byte array. + format: byte + nullable: true + type: string + normalArray: + description: byte array. + format: byte + type: string + nullableString: + nullable: true + type: string + stringField: + type: string + intField: + format: int32 + type: number + type: object + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/build.gradle b/samples/client/petstore/java/webclient-nulable-arrays/build.gradle new file mode 100644 index 00000000000..343400c83c2 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/build.gradle @@ -0,0 +1,141 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = 'v1' + +buildscript { + repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' + } +} + +repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() +} + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + install { + repositories.mavenInstaller { + pom.artifactId = 'petstore-webclient-nullable-arrays' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } + + task sourcesJar(type: Jar, dependsOn: classes) { + classifier = 'sources' + from sourceSets.main.allSource + } + + task javadocJar(type: Jar, dependsOn: javadoc) { + classifier = 'javadoc' + from javadoc.destinationDir + } + + artifacts { + archives sourcesJar + archives javadocJar + } +} + +ext { + swagger_annotations_version = "1.6.2" + spring_web_version = "2.4.3" + jackson_version = "2.11.3" + jackson_databind_version = "2.11.3" + jackson_databind_nullable_version = "0.2.1" + javax_annotation_version = "1.3.2" + reactor_version = "3.4.3" + reactor_netty_version = "0.7.15.RELEASE" + jodatime_version = "2.9.9" + junit_version = "4.13.1" +} + +dependencies { + implementation "io.swagger:swagger-annotations:$swagger_annotations_version" + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation "io.projectreactor:reactor-core:$reactor_version" + implementation "org.springframework.boot:spring-boot-starter-webflux:$spring_web_version" + implementation "io.projectreactor.ipc:reactor-netty:$reactor_netty_version" + implementation "com.fasterxml.jackson.core:jackson-core:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + implementation "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + implementation "javax.annotation:javax.annotation-api:$javax_annotation_version" + testImplementation "junit:junit:$junit_version" +} + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/build.sbt b/samples/client/petstore/java/webclient-nulable-arrays/build.sbt new file mode 100644 index 00000000000..464090415c4 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/build.sbt @@ -0,0 +1 @@ +# TODO diff --git a/samples/client/petstore/java/webclient-nulable-arrays/docs/ByteArrayObject.md b/samples/client/petstore/java/webclient-nulable-arrays/docs/ByteArrayObject.md new file mode 100644 index 00000000000..44cedf0bd5d --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/docs/ByteArrayObject.md @@ -0,0 +1,17 @@ + + +# ByteArrayObject + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**nullableArray** | **byte[]** | byte array. | [optional] +**normalArray** | **byte[]** | byte array. | [optional] +**nullableString** | **String** | | [optional] +**stringField** | **String** | | [optional] +**intField** | **BigDecimal** | | [optional] + + + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/docs/DefaultApi.md b/samples/client/petstore/java/webclient-nulable-arrays/docs/DefaultApi.md new file mode 100644 index 00000000000..6b52ac1cfc9 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/docs/DefaultApi.md @@ -0,0 +1,69 @@ +# DefaultApi + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**nullableArrayTestGet**](DefaultApi.md#nullableArrayTestGet) | **GET** /nullable-array-test | + + + +## nullableArrayTestGet + +> List<ByteArrayObject> nullableArrayTestGet() + + + +### 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.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + List result = apiInstance.nullableArrayTestGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#nullableArrayTestGet"); + 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 + +[**List<ByteArrayObject>**](ByteArrayObject.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | | - | + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/git_push.sh b/samples/client/petstore/java/webclient-nulable-arrays/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/gradle.properties b/samples/client/petstore/java/webclient-nulable-arrays/gradle.properties new file mode 100644 index 00000000000..05644f0754a --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/webclient-nulable-arrays/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/webclient-nulable-arrays/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..e708b1c023e Binary files /dev/null and b/samples/client/petstore/java/webclient-nulable-arrays/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/java/webclient-nulable-arrays/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/webclient-nulable-arrays/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..4d9ca164914 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/java/webclient-nulable-arrays/gradlew b/samples/client/petstore/java/webclient-nulable-arrays/gradlew new file mode 100644 index 00000000000..4f906e0c811 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/java/webclient-nulable-arrays/gradlew.bat b/samples/client/petstore/java/webclient-nulable-arrays/gradlew.bat new file mode 100644 index 00000000000..107acd32c4e --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/webclient-nulable-arrays/pom.xml b/samples/client/petstore/java/webclient-nulable-arrays/pom.xml new file mode 100644 index 00000000000..54c073f0f2e --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/pom.xml @@ -0,0 +1,138 @@ + + 4.0.0 + org.openapitools + petstore-webclient-nullable-arrays + jar + petstore-webclient-nullable-arrays + v1 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://unlicense.org + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.6.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + io.projectreactor + reactor-core + ${reactor-version} + + + + + org.springframework.boot + spring-boot-starter-webflux + ${spring-web-version} + + + + io.projectreactor.ipc + reactor-netty + ${reactor-netty-version} + + + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + javax.annotation + javax.annotation-api + ${javax-annotation-version} + provided + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.6.2 + 2.4.3 + 2.11.3 + 2.11.3 + 0.2.1 + 1.3.2 + 4.13.1 + 3.4.3 + 0.7.15.RELEASE + + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/settings.gradle b/samples/client/petstore/java/webclient-nulable-arrays/settings.gradle new file mode 100644 index 00000000000..7e909db80d1 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "petstore-webclient-nullable-arrays" \ No newline at end of file diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/AndroidManifest.xml b/samples/client/petstore/java/webclient-nulable-arrays/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..54fbcb3da1e --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 00000000000..87f4608c090 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,720 @@ +package org.openapitools.client; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.openapitools.jackson.nullable.JsonNullableModule; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.RequestEntity.BodyBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.http.codec.json.Jackson2JsonDecoder; +import org.springframework.http.codec.json.Jackson2JsonEncoder; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.http.client.reactive.ClientHttpRequest; +import org.springframework.web.client.RestClientException; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.web.reactive.function.client.WebClient; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; +import org.springframework.web.reactive.function.client.ClientResponse; +import org.springframework.web.reactive.function.BodyInserter; +import org.springframework.web.reactive.function.BodyInserters; +import org.springframework.web.reactive.function.client.ExchangeStrategies; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Flux; +import java.util.Optional; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimeZone; + +import javax.annotation.Nullable; + +import java.time.OffsetDateTime; + +import org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; +import org.openapitools.client.auth.ApiKeyAuth; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiClient extends JavaTimeFormatter { + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + private final String separator; + private CollectionFormat(String separator) { + this.separator = separator; + } + + private String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + private HttpHeaders defaultHeaders = new HttpHeaders(); + private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + + private String basePath = "http://localhost"; + + private final WebClient webClient; + private final DateFormat dateFormat; + private final ObjectMapper objectMapper; + + private Map authentications; + + + public ApiClient() { + this.dateFormat = createDefaultDateFormat(); + this.objectMapper = createDefaultObjectMapper(this.dateFormat); + this.webClient = buildWebClient(this.objectMapper); + this.init(); + } + + public ApiClient(WebClient webClient) { + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient()), createDefaultDateFormat()); + } + + public ApiClient(ObjectMapper mapper, DateFormat format) { + this(buildWebClient(mapper.copy()), format); + } + + public ApiClient(WebClient webClient, ObjectMapper mapper, DateFormat format) { + this(Optional.ofNullable(webClient).orElseGet(() -> buildWebClient(mapper.copy())), format); + } + + private ApiClient(WebClient webClient, DateFormat format) { + this.webClient = webClient; + this.dateFormat = format; + this.objectMapper = createDefaultObjectMapper(format); + this.init(); + } + + public static DateFormat createDefaultDateFormat() { + DateFormat dateFormat = new RFC3339DateFormat(); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + return dateFormat; + } + + public static ObjectMapper createDefaultObjectMapper(@Nullable DateFormat dateFormat) { + if (null == dateFormat) { + dateFormat = createDefaultDateFormat(); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.setDateFormat(dateFormat); + mapper.registerModule(new JavaTimeModule()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + return mapper; + } + + protected void init() { + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Build the WebClientBuilder used to make WebClient. + * @param mapper ObjectMapper used for serialize/deserialize + * @return WebClient + */ + public static WebClient.Builder buildWebClientBuilder(ObjectMapper mapper) { + ExchangeStrategies strategies = ExchangeStrategies + .builder() + .codecs(clientDefaultCodecsConfigurer -> { + clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(mapper, MediaType.APPLICATION_JSON)); + clientDefaultCodecsConfigurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(mapper, MediaType.APPLICATION_JSON)); + }).build(); + WebClient.Builder webClientBuilder = WebClient.builder().exchangeStrategies(strategies); + return webClientBuilder; + } + + /** + * Build the WebClientBuilder used to make WebClient. + * @return WebClient + */ + public static WebClient.Builder buildWebClientBuilder() { + return buildWebClientBuilder(createDefaultObjectMapper(null)); + } + + /** + * Build the WebClient used to make HTTP requests. + * @param mapper ObjectMapper used for serialize/deserialize + * @return WebClient + */ + public static WebClient buildWebClient(ObjectMapper mapper) { + return buildWebClientBuilder(mapper).build(); + } + + /** + * Build the WebClient used to make HTTP requests. + * @return WebClient + */ + public static WebClient buildWebClient() { + return buildWebClientBuilder(createDefaultObjectMapper(null)).build(); + } + + /** + * Get the current base path + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * @return Map the currently configured authentication types + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * @param username the username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password the password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * @param apiKey the API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix the API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + if (defaultHeaders.containsKey(name)) { + defaultHeaders.remove(name); + } + defaultHeaders.add(name, value); + return this; + } + + /** + * Add a default cookie. + * + * @param name The cookie's name + * @param value The cookie's value + * @return ApiClient this client + */ + public ApiClient addDefaultCookie(String name, String value) { + if (defaultCookies.containsKey(name)) { + defaultCookies.remove(name); + } + defaultCookies.add(name, value); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Parse the given string into Date object. + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Get the ObjectMapper used to make HTTP requests. + * @return ObjectMapper objectMapper + */ + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + /** + * Get the WebClient used to make HTTP requests. + * @return WebClient webClient + */ + public WebClient getWebClient() { + return webClient; + } + + /** + * Format the given parameter object into string. + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof OffsetDateTime) { + return formatOffsetDateTime((OffsetDateTime) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection) param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList(); + for(Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + // "* / *" is default to JSON + if ("*/*".equals(mediaType)) { + return true; + } + + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); + } + + /** + * Check if the given {@code String} is a Problem JSON MIME (RFC-7807). + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents Problem JSON, false otherwise + */ + public boolean isProblemJsonMime(String mediaType) { + return "application/problem+json".equalsIgnoreCase(mediaType); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, null will be returned. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected BodyInserter selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + if(MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)) { + MultiValueMap map = new LinkedMultiValueMap<>(); + + formParams + .toSingleValueMap() + .entrySet() + .forEach(es -> map.add(es.getKey(), String.valueOf(es.getValue()))); + + return BodyInserters.fromFormData(map); + } else if(MediaType.MULTIPART_FORM_DATA.equals(contentType)) { + return BodyInserters.fromMultipartData(formParams); + } else { + return obj != null ? BodyInserters.fromValue(obj) : null; + } + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param pathParams The path parameters + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in chosen type + */ + public ResponseSpec invokeAPI(String path, HttpMethod method, Map pathParams, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + final WebClient.RequestBodySpec requestBuilder = prepareRequest(path, method, pathParams, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames); + return requestBuilder.retrieve(); + } + + /** + * Include queryParams in uriParams taking into account the paramName + * @param queryParam The query parameters + * @param uriParams The path parameters + * return templatized query string + */ + private String generateQueryUri(MultiValueMap queryParams, Map uriParams) { + StringBuilder queryBuilder = new StringBuilder(); + queryParams.forEach((name, values) -> { + if (CollectionUtils.isEmpty(values)) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(name); + } else { + int valueItemCounter = 0; + for (Object value : values) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(name); + if (value != null) { + String templatizedKey = name + valueItemCounter++; + uriParams.put(templatizedKey, value.toString()); + queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + } + } + } + }); + return queryBuilder.toString(); + } + + private WebClient.RequestBodySpec prepareRequest(String path, HttpMethod method, Map pathParams, + MultiValueMap queryParams, Object body, HttpHeaders headerParams, + MultiValueMap cookieParams, MultiValueMap formParams, List accept, + MediaType contentType, String[] authNames) { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path); + + String finalUri = builder.build(false).toUriString(); + Map uriParams = new HashMap(); + uriParams.putAll(pathParams); + + if (queryParams != null && !queryParams.isEmpty()) { + //Include queryParams in uriParams taking into account the paramName + String queryUri = generateQueryUri(queryParams, uriParams); + //Append to finalUri the templatized query string like "?param1={param1Value}&....... + finalUri += "?" + queryUri; + } + + final WebClient.RequestBodySpec requestBuilder = webClient.method(method).uri(finalUri, uriParams); + + if (accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if(contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + addCookiesToRequest(cookieParams, requestBuilder); + addCookiesToRequest(defaultCookies, requestBuilder); + + requestBuilder.body(selectBody(body, formParams, contentType)); + return requestBuilder; + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, WebClient.RequestBodySpec requestBuilder) { + for (Entry> entry : headers.entrySet()) { + List values = entry.getValue(); + for(String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Add cookies to the request that is being built + * @param cookies The cookies to add + * @param requestBuilder The current request + */ + protected void addCookiesToRequest(MultiValueMap cookies, WebClient.RequestBodySpec requestBuilder) { + for (Entry> entry : cookies.entrySet()) { + List values = entry.getValue(); + for(String value : values) { + if (value != null) { + requestBuilder.cookie(entry.getKey(), value); + } + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + * @param cookieParams the cookie parameters + */ + private void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RestClientException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams); + } + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param values The values of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection values) { + // create the value based on the collection format + if (CollectionFormat.MULTI.equals(collectionFormat)) { + // not valid for path params + return parameterToString(values); + } + + // collectionFormat is assumed to be "csv" by default + if(collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + return collectionFormat.collectionToString(values); + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/JavaTimeFormatter.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/JavaTimeFormatter.java new file mode 100644 index 00000000000..9e5bee7fcce --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/JavaTimeFormatter.java @@ -0,0 +1,64 @@ +/* + * Minimal Example + * byte Array error in equal method + * + * The version of the OpenAPI document: v1 + * + * + * 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; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 00000000000..e8c4b6e227a --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,55 @@ +/* + * Minimal Example + * byte Array error in equal method + * + * The version of the OpenAPI document: v1 + * + * + * 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; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 00000000000..a1107a8690e --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A describtion of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replaceAll("\\{" + name + "\\}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ServerVariable.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 00000000000..c2f13e21666 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,23 @@ +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/StringUtil.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 00000000000..93f5432910d --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * Minimal Example + * byte Array error in equal method + * + * The version of the OpenAPI document: v1 + * + * + * 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; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/api/DefaultApi.java new file mode 100644 index 00000000000..6e17adf4454 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -0,0 +1,96 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiClient; + +import org.openapitools.client.model.ByteArrayObject; + +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.web.reactive.function.client.WebClient.ResponseSpec; +import org.springframework.web.reactive.function.client.WebClientResponseException; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Flux; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DefaultApi { + private ApiClient apiClient; + + public DefaultApi() { + this(new ApiClient()); + } + + @Autowired + public DefaultApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * + * + *

200 + * @return List<ByteArrayObject> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec nullableArrayTestGetRequestCreation() throws WebClientResponseException { + Object postBody = null; + // create path and map variables + final Map pathParams = new HashMap(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/nullable-array-test", HttpMethod.GET, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * + * + *

200 + * @return List<ByteArrayObject> + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Flux nullableArrayTestGet() throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return nullableArrayTestGetRequestCreation().bodyToFlux(localVarReturnType); + } + + public Mono>> nullableArrayTestGetWithHttpInfo() throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return nullableArrayTestGetRequestCreation().toEntityList(localVarReturnType); + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..9e9f3733160 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,62 @@ +package org.openapitools.client.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } else if (location.equals("cookie")) { + cookieParams.add(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 00000000000..4f9a14ebd7c --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,14 @@ +package org.openapitools.client.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + * @param cookieParams The cookie parameters for the request + */ + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams); +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..bbbbba67a47 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,39 @@ +package org.openapitools.client.auth; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.Base64Utils; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 00000000000..775bbf64c3b --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,39 @@ +package org.openapitools.client.auth; + +import java.io.UnsupportedEncodingException; +import java.nio.charset.StandardCharsets; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.Base64Utils; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + public String getBearerToken() { + return bearerToken; + } + + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (bearerToken == null) { + return; + } + headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } + +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/model/ByteArrayObject.java b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/model/ByteArrayObject.java new file mode 100644 index 00000000000..0f1960813ae --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/main/java/org/openapitools/client/model/ByteArrayObject.java @@ -0,0 +1,271 @@ +/* + * Minimal Example + * byte Array error in equal method + * + * The version of the OpenAPI document: v1 + * + * + * 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.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.math.BigDecimal; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; + +/** + * ByteArrayObject + */ +@JsonPropertyOrder({ + ByteArrayObject.JSON_PROPERTY_NULLABLE_ARRAY, + ByteArrayObject.JSON_PROPERTY_NORMAL_ARRAY, + ByteArrayObject.JSON_PROPERTY_NULLABLE_STRING, + ByteArrayObject.JSON_PROPERTY_STRING_FIELD, + ByteArrayObject.JSON_PROPERTY_INT_FIELD +}) +@JsonTypeName("ByteArrayObject") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ByteArrayObject { + public static final String JSON_PROPERTY_NULLABLE_ARRAY = "nullableArray"; + private JsonNullable nullableArray = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_NORMAL_ARRAY = "normalArray"; + private byte[] normalArray; + + public static final String JSON_PROPERTY_NULLABLE_STRING = "nullableString"; + private JsonNullable nullableString = JsonNullable.undefined(); + + public static final String JSON_PROPERTY_STRING_FIELD = "stringField"; + private String stringField; + + public static final String JSON_PROPERTY_INT_FIELD = "intField"; + private BigDecimal intField; + + + public ByteArrayObject nullableArray(byte[] nullableArray) { + this.nullableArray = JsonNullable.of(nullableArray); + + return this; + } + + /** + * byte array. + * @return nullableArray + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "byte array.") + @JsonIgnore + + public byte[] getNullableArray() { + return nullableArray.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_NULLABLE_ARRAY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable getNullableArray_JsonNullable() { + return nullableArray; + } + + @JsonProperty(JSON_PROPERTY_NULLABLE_ARRAY) + public void setNullableArray_JsonNullable(JsonNullable nullableArray) { + this.nullableArray = nullableArray; + } + + public void setNullableArray(byte[] nullableArray) { + this.nullableArray = JsonNullable.of(nullableArray); + } + + + public ByteArrayObject normalArray(byte[] normalArray) { + + this.normalArray = normalArray; + return this; + } + + /** + * byte array. + * @return normalArray + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "byte array.") + @JsonProperty(JSON_PROPERTY_NORMAL_ARRAY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public byte[] getNormalArray() { + return normalArray; + } + + + @JsonProperty(JSON_PROPERTY_NORMAL_ARRAY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNormalArray(byte[] normalArray) { + this.normalArray = normalArray; + } + + + public ByteArrayObject nullableString(String nullableString) { + this.nullableString = JsonNullable.of(nullableString); + + return this; + } + + /** + * Get nullableString + * @return nullableString + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonIgnore + + public String getNullableString() { + return nullableString.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_NULLABLE_STRING) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable getNullableString_JsonNullable() { + return nullableString; + } + + @JsonProperty(JSON_PROPERTY_NULLABLE_STRING) + public void setNullableString_JsonNullable(JsonNullable nullableString) { + this.nullableString = nullableString; + } + + public void setNullableString(String nullableString) { + this.nullableString = JsonNullable.of(nullableString); + } + + + public ByteArrayObject stringField(String stringField) { + + this.stringField = stringField; + return this; + } + + /** + * Get stringField + * @return stringField + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_STRING_FIELD) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getStringField() { + return stringField; + } + + + @JsonProperty(JSON_PROPERTY_STRING_FIELD) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setStringField(String stringField) { + this.stringField = stringField; + } + + + public ByteArrayObject intField(BigDecimal intField) { + + this.intField = intField; + return this; + } + + /** + * Get intField + * @return intField + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_INT_FIELD) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public BigDecimal getIntField() { + return intField; + } + + + @JsonProperty(JSON_PROPERTY_INT_FIELD) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setIntField(BigDecimal intField) { + this.intField = intField; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ByteArrayObject byteArrayObject = (ByteArrayObject) o; + return equalsNullable(this.nullableArray, byteArrayObject.nullableArray) && + Arrays.equals(this.normalArray, byteArrayObject.normalArray) && + equalsNullable(this.nullableString, byteArrayObject.nullableString) && + Objects.equals(this.stringField, byteArrayObject.stringField) && + Objects.equals(this.intField, byteArrayObject.intField); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(hashCodeNullable(nullableArray), Arrays.hashCode(normalArray), hashCodeNullable(nullableString), stringField, intField); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ByteArrayObject {\n"); + sb.append(" nullableArray: ").append(toIndentedString(nullableArray)).append("\n"); + sb.append(" normalArray: ").append(toIndentedString(normalArray)).append("\n"); + sb.append(" nullableString: ").append(toIndentedString(nullableString)).append("\n"); + sb.append(" stringField: ").append(toIndentedString(stringField)).append("\n"); + sb.append(" intField: ").append(toIndentedString(intField)).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 "); + } + +} + diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/test/java/org/openapitools/client/api/DefaultApiTest.java b/samples/client/petstore/java/webclient-nulable-arrays/src/test/java/org/openapitools/client/api/DefaultApiTest.java new file mode 100644 index 00000000000..6c15be4ff81 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/test/java/org/openapitools/client/api/DefaultApiTest.java @@ -0,0 +1,47 @@ +/* + * Minimal Example + * byte Array error in equal method + * + * The version of the OpenAPI document: v1 + * + * + * 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.model.ByteArrayObject; +import org.junit.Test; +import org.junit.Ignore; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * API tests for DefaultApi + */ +@Ignore +public class DefaultApiTest { + + private final DefaultApi api = new DefaultApi(); + + + /** + * + * + * + */ + @Test + public void nullableArrayTestGetTest() { + List response = api.nullableArrayTestGet().collectList().block(); + + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/webclient-nulable-arrays/src/test/java/org/openapitools/client/model/ByteArrayObjectTest.java b/samples/client/petstore/java/webclient-nulable-arrays/src/test/java/org/openapitools/client/model/ByteArrayObjectTest.java new file mode 100644 index 00000000000..aff761e19e6 --- /dev/null +++ b/samples/client/petstore/java/webclient-nulable-arrays/src/test/java/org/openapitools/client/model/ByteArrayObjectTest.java @@ -0,0 +1,61 @@ +/* + * Minimal Example + * byte Array error in equal method + * + * The version of the OpenAPI document: v1 + * + * + * 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.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ByteArrayObject + */ +public class ByteArrayObjectTest { + private final ByteArrayObject model = new ByteArrayObject(); + + /** + * Model tests for ByteArrayObject + */ + @Test + public void testByteArrayObject() { + // TODO: test ByteArrayObject + } + + /** + * Test the property 'nullableArray' + */ + @Test + public void nullableArrayTest() { + // TODO: test nullableArray + } + + /** + * Test the property 'normalArray' + */ + @Test + public void normalArrayTest() { + // TODO: test normalArray + } + +} diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java index c9e35dd1b5e..a2bc31cdab7 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/EnumTest.java @@ -26,6 +26,7 @@ import org.openapitools.client.model.OuterEnum; import org.openapitools.client.model.OuterEnumDefaultValue; import org.openapitools.client.model.OuterEnumInteger; import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -453,15 +454,28 @@ public class EnumTest { Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && Objects.equals(this.enumInteger, enumTest.enumInteger) && Objects.equals(this.enumNumber, enumTest.enumNumber) && - Objects.equals(this.outerEnum, enumTest.outerEnum) && + equalsNullable(this.outerEnum, enumTest.outerEnum) && Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(enumString, enumStringRequired, enumInteger, enumNumber, outerEnum, outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); + return Objects.hash(enumString, enumStringRequired, enumInteger, enumNumber, hashCodeNullable(outerEnum), outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java index fca0af36793..9ca1ed06b50 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -85,12 +86,25 @@ public class HealthCheckResult { return false; } HealthCheckResult healthCheckResult = (HealthCheckResult) o; - return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage); + return equalsNullable(this.nullableMessage, healthCheckResult.nullableMessage); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); } @Override public int hashCode() { - return Objects.hash(nullableMessage); + return Objects.hash(hashCodeNullable(nullableMessage)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java index 303ba0aeb76..fee8d1fa00e 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/NullableClass.java @@ -29,6 +29,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -568,24 +569,37 @@ public class NullableClass extends HashMap { return false; } NullableClass nullableClass = (NullableClass) o; - return Objects.equals(this.integerProp, nullableClass.integerProp) && - Objects.equals(this.numberProp, nullableClass.numberProp) && - Objects.equals(this.booleanProp, nullableClass.booleanProp) && - Objects.equals(this.stringProp, nullableClass.stringProp) && - Objects.equals(this.dateProp, nullableClass.dateProp) && - Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && - Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && - Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && + return equalsNullable(this.integerProp, nullableClass.integerProp) && + equalsNullable(this.numberProp, nullableClass.numberProp) && + equalsNullable(this.booleanProp, nullableClass.booleanProp) && + equalsNullable(this.stringProp, nullableClass.stringProp) && + equalsNullable(this.dateProp, nullableClass.dateProp) && + equalsNullable(this.datetimeProp, nullableClass.datetimeProp) && + equalsNullable(this.arrayNullableProp, nullableClass.arrayNullableProp) && + equalsNullable(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && - Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && - Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && + equalsNullable(this.objectNullableProp, nullableClass.objectNullableProp) && + equalsNullable(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable) && super.equals(o); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, super.hashCode()); + return Objects.hash(hashCodeNullable(integerProp), hashCodeNullable(numberProp), hashCodeNullable(booleanProp), hashCodeNullable(stringProp), hashCodeNullable(dateProp), hashCodeNullable(datetimeProp), hashCodeNullable(arrayNullableProp), hashCodeNullable(arrayAndItemsNullableProp), arrayItemsNullable, hashCodeNullable(objectNullableProp), hashCodeNullable(objectAndItemsNullableProp), objectItemsNullable, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 5742109fbf2..bc5318f3f9e 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -27,6 +27,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -336,7 +337,7 @@ public class AdditionalPropertiesClass { AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty) && - Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && + equalsNullable(this.anytype1, additionalPropertiesClass.anytype1) && Objects.equals(this.mapWithUndeclaredPropertiesAnytype1, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype1) && Objects.equals(this.mapWithUndeclaredPropertiesAnytype2, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype2) && Objects.equals(this.mapWithUndeclaredPropertiesAnytype3, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype3) && @@ -344,9 +345,22 @@ public class AdditionalPropertiesClass { Objects.equals(this.mapWithUndeclaredPropertiesString, additionalPropertiesClass.mapWithUndeclaredPropertiesString); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(mapProperty, mapOfMapProperty, anytype1, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, emptyMap, mapWithUndeclaredPropertiesString); + return Objects.hash(mapProperty, mapOfMapProperty, hashCodeNullable(anytype1), mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, emptyMap, mapWithUndeclaredPropertiesString); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/Drawing.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/Drawing.java index d0f7d455d57..eb2ce538d97 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/Drawing.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/Drawing.java @@ -34,6 +34,7 @@ import org.openapitools.client.model.Fruit; import org.openapitools.client.model.NullableShape; import org.openapitools.client.model.Shape; import org.openapitools.client.model.ShapeOrNull; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -236,14 +237,27 @@ public class Drawing { Drawing drawing = (Drawing) o; return Objects.equals(this.mainShape, drawing.mainShape) && Objects.equals(this.shapeOrNull, drawing.shapeOrNull) && - Objects.equals(this.nullableShape, drawing.nullableShape) && + equalsNullable(this.nullableShape, drawing.nullableShape) && Objects.equals(this.shapes, drawing.shapes)&& Objects.equals(this.additionalProperties, drawing.additionalProperties); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(mainShape, shapeOrNull, nullableShape, shapes, additionalProperties); + return Objects.hash(mainShape, shapeOrNull, hashCodeNullable(nullableShape), shapes, additionalProperties); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/EnumTest.java index 4c34c78d7a0..7304f015f29 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/EnumTest.java @@ -28,6 +28,7 @@ import org.openapitools.client.model.OuterEnum; import org.openapitools.client.model.OuterEnumDefaultValue; import org.openapitools.client.model.OuterEnumInteger; import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -517,15 +518,28 @@ public class EnumTest { Objects.equals(this.enumInteger, enumTest.enumInteger) && Objects.equals(this.enumIntegerOnly, enumTest.enumIntegerOnly) && Objects.equals(this.enumNumber, enumTest.enumNumber) && - Objects.equals(this.outerEnum, enumTest.outerEnum) && + equalsNullable(this.outerEnum, enumTest.outerEnum) && Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(enumString, enumStringRequired, enumInteger, enumIntegerOnly, enumNumber, outerEnum, outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); + return Objects.hash(enumString, enumStringRequired, enumInteger, enumIntegerOnly, enumNumber, hashCodeNullable(outerEnum), outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/HealthCheckResult.java index 3e67cd1c84c..71a5e8e2c9f 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -90,12 +91,25 @@ public class HealthCheckResult { return false; } HealthCheckResult healthCheckResult = (HealthCheckResult) o; - return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage); + return equalsNullable(this.nullableMessage, healthCheckResult.nullableMessage); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); } @Override public int hashCode() { - return Objects.hash(nullableMessage); + return Objects.hash(hashCodeNullable(nullableMessage)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/NullableClass.java index 2ee8e3a9954..2163e1535b8 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/NullableClass.java @@ -35,6 +35,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -603,24 +604,37 @@ public class NullableClass { return false; } NullableClass nullableClass = (NullableClass) o; - return Objects.equals(this.integerProp, nullableClass.integerProp) && - Objects.equals(this.numberProp, nullableClass.numberProp) && - Objects.equals(this.booleanProp, nullableClass.booleanProp) && - Objects.equals(this.stringProp, nullableClass.stringProp) && - Objects.equals(this.dateProp, nullableClass.dateProp) && - Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && - Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && - Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && + return equalsNullable(this.integerProp, nullableClass.integerProp) && + equalsNullable(this.numberProp, nullableClass.numberProp) && + equalsNullable(this.booleanProp, nullableClass.booleanProp) && + equalsNullable(this.stringProp, nullableClass.stringProp) && + equalsNullable(this.dateProp, nullableClass.dateProp) && + equalsNullable(this.datetimeProp, nullableClass.datetimeProp) && + equalsNullable(this.arrayNullableProp, nullableClass.arrayNullableProp) && + equalsNullable(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && - Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && - Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && + equalsNullable(this.objectNullableProp, nullableClass.objectNullableProp) && + equalsNullable(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable)&& Objects.equals(this.additionalProperties, nullableClass.additionalProperties); } + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); + } + @Override public int hashCode() { - return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, additionalProperties); + return Objects.hash(hashCodeNullable(integerProp), hashCodeNullable(numberProp), hashCodeNullable(booleanProp), hashCodeNullable(stringProp), hashCodeNullable(dateProp), hashCodeNullable(datetimeProp), hashCodeNullable(arrayNullableProp), hashCodeNullable(arrayAndItemsNullableProp), arrayItemsNullable, hashCodeNullable(objectNullableProp), hashCodeNullable(objectAndItemsNullableProp), objectItemsNullable, additionalProperties); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/User.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/User.java index 0c27f6fba98..3644c760842 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/User.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/User.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import org.openapitools.jackson.nullable.JsonNullable; import com.fasterxml.jackson.annotation.JsonIgnore; import org.openapitools.jackson.nullable.JsonNullable; import java.util.NoSuchElementException; @@ -444,14 +445,27 @@ public class User { Objects.equals(this.phone, user.phone) && Objects.equals(this.userStatus, user.userStatus) && Objects.equals(this.objectWithNoDeclaredProps, user.objectWithNoDeclaredProps) && - Objects.equals(this.objectWithNoDeclaredPropsNullable, user.objectWithNoDeclaredPropsNullable) && - Objects.equals(this.anyTypeProp, user.anyTypeProp) && - Objects.equals(this.anyTypePropNullable, user.anyTypePropNullable); + equalsNullable(this.objectWithNoDeclaredPropsNullable, user.objectWithNoDeclaredPropsNullable) && + equalsNullable(this.anyTypeProp, user.anyTypeProp) && + equalsNullable(this.anyTypePropNullable, user.anyTypePropNullable); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && a.get().getClass().isArray() ? Arrays.equals((T[])a.get(), (T[])b.get()) : Objects.equals(a.get(), b.get())); } @Override public int hashCode() { - return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, anyTypeProp, anyTypePropNullable); + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus, objectWithNoDeclaredProps, hashCodeNullable(objectWithNoDeclaredPropsNullable), hashCodeNullable(anyTypeProp), hashCodeNullable(anyTypePropNullable)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() + ? (a.get().getClass().isArray() ? Arrays.hashCode((T[])a.get()) : Objects.hashCode(a.get())) + : 31; } @Override