From ed2aad6756db1dfc780f709f0a6ee0feeb00f31a Mon Sep 17 00:00:00 2001 From: Philzen Date: Sun, 2 Jun 2024 15:42:55 +0200 Subject: [PATCH] [JAVA: okhttp-gson, rest-assured, retrofit2] Don't generate Jackson import when serialization library is GSON (#18811) * Partially revert "replace deprecated ISO8601Utils with StdDateFormat (#17052)" This partially reverts commit 76560e34c9aacd9d7593ac45bd204e2edf38abd9, namely anything related to generators and samples using GSON instead of Jackson. Changes to Jackson-only generation and generator-online regarding RFC3339DateFormat are not being reverted. * Test for default serialization library fallback * Convert repetitive tests to parameterized test * Add regression test for #18515 * [FEIGN] Only include property in pom.xml when required * [RETROFIT2] Only include jackson-databind in gradle file when actually required * [FEIGN] Don't include jackson dep's in sbt file when GSON is selected * [FEIGN] Don't include jackson dep's in gradle file when GSON is selected * DRY refactor JavaClientCodegen test code, increase readability - use fluent assertions - use helper method newTempFolder() - use Java 9 static factory methods for maps - don't declare variables that are only used once - group declarations and usages - use non-blocking java.nio.file API wherever possible * Regenerate samples --- .../codegen/online/RFC3339DateFormat.java | 26 +- .../src/main/resources/Java/JSON.mustache | 18 +- .../libraries/feign/build.gradle.mustache | 14 +- .../Java/libraries/feign/build.sbt.mustache | 4 + .../Java/libraries/feign/pom.mustache | 2 +- .../Java/libraries/okhttp-gson/JSON.mustache | 19 +- .../Java/libraries/rest-assured/pom.mustache | 11 +- .../Java/libraries/retrofit2/JSON.mustache | 18 +- .../libraries/retrofit2/build.gradle.mustache | 8 +- .../Java/libraries/retrofit2/pom.mustache | 21 +- .../codegen/java/JavaClientCodegenTest.java | 3179 ++++++----------- .../echo_api/java/feign-gson/build.gradle | 7 - .../client/echo_api/java/feign-gson/build.sbt | 6 - .../client/echo_api/java/feign-gson/pom.xml | 1 - .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../client/petstore/java/feign/build.gradle | 2 +- samples/client/petstore/java/feign/pom.xml | 2 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../java/org/openapitools/client/JSON.java | 19 +- .../client/petstore/java/okhttp-gson/pom.xml | 6 - .../java/org/openapitools/client/JSON.java | 19 +- .../java/rest-assured-jackson/pom.xml | 11 +- .../client/petstore/java/rest-assured/pom.xml | 6 - .../java/org/openapitools/client/JSON.java | 18 +- .../java/retrofit2-play26/build.gradle | 4 +- .../petstore/java/retrofit2-play26/pom.xml | 15 +- .../petstore/java/retrofit2/build.gradle | 2 - .../client/petstore/java/retrofit2/pom.xml | 6 - .../java/org/openapitools/client/JSON.java | 18 +- .../petstore/java/retrofit2rx2/build.gradle | 2 - .../client/petstore/java/retrofit2rx2/pom.xml | 6 - .../java/org/openapitools/client/JSON.java | 18 +- .../petstore/java/retrofit2rx3/build.gradle | 2 - .../client/petstore/java/retrofit2rx3/pom.xml | 6 - .../java/org/openapitools/client/JSON.java | 18 +- 44 files changed, 1340 insertions(+), 2383 deletions(-) diff --git a/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/RFC3339DateFormat.java b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/RFC3339DateFormat.java index 9a089de40c3..fa2752bd6f8 100644 --- a/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/RFC3339DateFormat.java +++ b/modules/openapi-generator-online/src/main/java/org/openapitools/codegen/online/RFC3339DateFormat.java @@ -17,35 +17,23 @@ package org.openapitools.codegen.online; -import com.fasterxml.jackson.databind.util.StdDateFormat; +import com.fasterxml.jackson.databind.util.ISO8601DateFormat; +import com.fasterxml.jackson.databind.util.ISO8601Utils; -import java.text.DateFormat; import java.text.FieldPosition; -import java.text.ParsePosition; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; import java.util.Date; -import java.util.TimeZone; -public class RFC3339DateFormat extends DateFormat { + +public class RFC3339DateFormat extends ISO8601DateFormat { private static final long serialVersionUID = 1L; - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); + // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + String value = ISO8601Utils.format(date, true); toAppendTo.append(value); return toAppendTo; } - @Override - public Date parse(String source, ParsePosition pos) { - return sdf.parse(source, pos); - } - -} +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/JSON.mustache index 0b4651d7928..1d0a8138787 100644 --- a/modules/openapi-generator/src/main/resources/Java/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/JSON.mustache @@ -2,11 +2,11 @@ package {{invokerPackage}}; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -33,14 +33,11 @@ import java.text.ParseException; import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; public class JSON { private Gson gson; @@ -57,11 +54,6 @@ public class JSON { {{/jsr310}} private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -469,7 +461,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -479,7 +471,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -504,7 +496,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -523,7 +515,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache index d4b2c8fcc52..8af1cb136e5 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.gradle.mustache @@ -102,8 +102,10 @@ test { ext { swagger_annotations_version = "1.6.11" + {{#jackson}} jackson_version = "2.17.1" jackson_databind_version = "2.17.1" + {{/jackson}} {{#openApiNullable}} jackson_databind_nullable_version = "0.2.6" {{/openApiNullable}} @@ -118,20 +120,24 @@ dependencies { implementation "io.swagger:swagger-annotations:$swagger_annotations_version" implementation "com.google.code.findbugs:jsr305:3.0.2" implementation "io.github.openfeign:feign-core:$feign_version" + {{#jackson}} implementation "io.github.openfeign:feign-jackson:$feign_version" + {{/jackson}} implementation "io.github.openfeign:feign-slf4j:$feign_version" implementation "io.github.openfeign:feign-okhttp:$feign_version" implementation "io.github.openfeign.form:feign-form:$feign_form_version" + {{#jackson}} + {{#joda}} + implementation "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" + {{/joda}} 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.datatype:jackson-datatype-jsr310:$jackson_version" + {{/jackson}} {{#openApiNullable}} implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" {{/openApiNullable}} - {{#joda}} - implementation "com.fasterxml.jackson.datatype:jackson-datatype-joda:$jackson_version" - {{/joda}} - implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" implementation "com.brsanthu:migbase64:2.2" implementation "com.github.scribejava:scribejava-core:$scribejava_version" implementation "com.brsanthu:migbase64:2.2" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache index 56043e581b4..9af32c27022 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/build.sbt.mustache @@ -12,15 +12,19 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.6.11" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "io.github.openfeign" % "feign-core" % "10.12" % "compile", +{{#jackson}} "io.github.openfeign" % "feign-jackson" % "10.12" % "compile", +{{/jackson}} "io.github.openfeign" % "feign-slf4j" % "10.12" % "compile", "io.github.openfeign.form" % "feign-form" % "3.8.0" % "compile", "io.github.openfeign" % "feign-okhttp" % "10.12" % "compile", +{{#jackson}} "com.fasterxml.jackson.core" % "jackson-core" % "2.17.1" % "compile", "com.fasterxml.jackson.core" % "jackson-annotations" % "2.17.1" % "compile", "com.fasterxml.jackson.core" % "jackson-databind" % "2.17.1" % "compile", "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.17.1" % "compile", "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.15.2" % "compile", +{{/jackson}} "com.github.scribejava" % "scribejava-core" % "8.0.0" % "compile", "com.brsanthu" % "migbase64" % "2.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache index 2f597ef432f..9be4a094faf 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache @@ -393,6 +393,7 @@ 3.8.0 {{#jackson}} 2.17.1 + 2.17.1 {{/jackson}} {{#gson}} 2.10.1 @@ -400,7 +401,6 @@ {{#openApiNullable}} 0.2.6 {{/openApiNullable}} - 2.17.1 {{#useJakartaEe}} 2.1.1 {{/useJakartaEe}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index c6075a08694..6cf7ec7898c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -2,11 +2,11 @@ package {{invokerPackage}}; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -27,16 +27,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -59,11 +57,6 @@ public class JSON { {{/jsr310}} private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -466,7 +459,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -476,7 +469,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -501,7 +494,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -520,7 +513,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache index 4757ca28c27..3523ed4fc8d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache @@ -271,11 +271,6 @@ ${gson-fire-version} {{/gson}} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - {{#jackson}} @@ -286,6 +281,10 @@ com.fasterxml.jackson.core jackson-annotations + + com.fasterxml.jackson.core + jackson-databind + org.openapitools jackson-databind-nullable @@ -352,9 +351,9 @@ {{#joda}} 2.10.5 {{/joda}} - 2.17.1 {{#jackson}} 2.17.1 + 2.17.1 0.2.6 {{/jackson}} {{#useJakartaEe}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/JSON.mustache index 2d791d4ff58..2ff8b1cb739 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/JSON.mustache @@ -2,11 +2,11 @@ package {{invokerPackage}}; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -32,14 +32,11 @@ import java.text.ParseException; import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; public class JSON { private Gson gson; @@ -54,11 +51,6 @@ public class JSON { private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); {{/jsr310}} - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() {{#models}}{{#model}}{{#discriminator}} .registerTypeSelector({{classname}}.class, new TypeSelector() { @@ -370,7 +362,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -380,7 +372,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -406,7 +398,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -425,7 +417,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index 4a2d43d665c..fdd5705c57b 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -99,13 +99,13 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - jackson_databind_version = "2.17.1" {{#jackson}} jackson_version = "2.17.1" + jackson_databind_version = "2.17.1" javax_ws_rs_api_version = "2.1.1" - {{#openApiNullable}} + {{#openApiNullable}} jackson_databind_nullable_version = "0.2.6" - {{/openApiNullable}} + {{/openApiNullable}} {{/jackson}} {{#usePlayWS}} play_version = "2.6.7" @@ -154,13 +154,13 @@ dependencies { implementation "com.squareup.retrofit2:converter-jackson:$retrofit_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 "javax.ws.rs:javax.ws.rs-api:$javax_ws_rs_api_version" {{#openApiNullable}} implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" {{/openApiNullable}} implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" {{/jackson}} - implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" testImplementation "junit:junit:$junit_version" } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache index f973562090e..8336f99ffdb 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -211,11 +211,6 @@ swagger-annotations ${swagger-annotations-version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - com.google.code.findbugs @@ -305,6 +300,11 @@ jackson-annotations ${jackson-version} + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + {{#openApiNullable}} org.openapitools @@ -344,6 +344,11 @@ play-ahc-ws_2.12 ${play-version} + + jakarta.validation + jakarta.validation-api + ${beanvalidation-version} + {{/usePlayWS}} {{#parcelableModel}} @@ -377,12 +382,12 @@ 1.9.0 {{/gson}} 1.6.3 - 2.17.1 {{#jackson}} + 2.17.1 2.17.1 - {{#openApiNullable}} + {{#openApiNullable}} 0.2.6 - {{/openApiNullable}} + {{/openApiNullable}} 2.1.1 {{/jackson}} {{#usePlayWS}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index 0a5590dae84..878e9358a02 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -17,67 +17,19 @@ package org.openapitools.codegen.java; -import org.junit.jupiter.api.Assertions; -import static org.openapitools.codegen.TestUtils.assertFileContains; -import static org.openapitools.codegen.TestUtils.assertFileNotContains; -import static org.openapitools.codegen.TestUtils.validateJavaSourceFiles; -import static org.openapitools.codegen.languages.JavaClientCodegen.USE_ENUM_CASE_INSENSITIVE; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertTrue; -import static org.testng.Assert.fail; - import com.google.common.collect.ImmutableMap; import io.swagger.parser.OpenAPIParser; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.media.ArraySchema; -import io.swagger.v3.oas.models.media.ComposedSchema; -import io.swagger.v3.oas.models.media.Content; -import io.swagger.v3.oas.models.media.IntegerSchema; -import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.ObjectSchema; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.media.StringSchema; +import io.swagger.v3.oas.models.media.*; import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.parser.core.models.ParseOptions; import io.swagger.v3.parser.util.SchemaTypeUtil; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; - +import lombok.Getter; import lombok.SneakyThrows; -import org.openapitools.codegen.ClientOptInput; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenModel; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenParameter; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.CodegenResponse; -import org.openapitools.codegen.CodegenSecurity; -import org.openapitools.codegen.DefaultGenerator; -import org.openapitools.codegen.TestUtils; +import org.junit.jupiter.api.Assertions; +import org.openapitools.codegen.*; import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.java.assertions.JavaFileAssert; import org.openapitools.codegen.languages.AbstractJavaCodegen; @@ -87,41 +39,107 @@ import org.openapitools.codegen.languages.features.CXFServerFeatures; import org.openapitools.codegen.meta.features.SecurityFeature; import org.openapitools.codegen.model.OperationMap; import org.openapitools.codegen.model.OperationsMap; -import org.testng.Assert; import org.testng.annotations.DataProvider; -import org.testng.annotations.Ignore; import org.testng.annotations.Test; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.entry; +import static org.openapitools.codegen.CodegenConstants.SERIALIZATION_LIBRARY; +import static org.openapitools.codegen.TestUtils.validateJavaSourceFiles; +import static org.openapitools.codegen.languages.JavaClientCodegen.*; +import static org.testng.Assert.*; + public class JavaClientCodegenTest { - @Test - public void arraysInRequestBody() { + // This is the kind of information that ideally would be defined and available system-wide + @Getter enum Library { + APACHE_HTTPCLIENT("apache-httpclient", Serializer.JACKSON), + FEIGN("feign", Serializer.JACKSON, Set.of(Serializer.GSON)), + GOOGLE_API_CLIENT("google-api-client", Serializer.JACKSON), + JERSEY_2("jersey2", Serializer.JACKSON), + JERSEY_3("jersey3", Serializer.JACKSON), + MICROPROFILE("microprofile", Serializer.JSONB, Set.of(Serializer.JACKSON)), + NATIVE("native", Serializer.JACKSON), + OKHTTP("okhttp-gson", Serializer.GSON), + REST_ASSURED("rest-assured", Serializer.GSON, Set.of(Serializer.JACKSON)), + RESTEASY("resteasy", Serializer.JACKSON), + REST_CLIENT("restclient", Serializer.JACKSON), + REST_TEMPLATE("resttemplate", Serializer.JACKSON), + RETROFIT_2("retrofit2", Serializer.GSON), + VERTX("vertx", Serializer.JACKSON), + WEBCLIENT("webclient", Serializer.JACKSON); + + public final String value; + public final Set supportedSerializers; + public final Serializer defaultSerializer; + + Library(String identifier, Serializer defaultSerializer) { + this(identifier, defaultSerializer, Set.of()); + } + + Library(String identifier, Serializer defaultSerializer, Set otherSupportedSerializers) { + otherSupportedSerializers = new HashSet<>(otherSupportedSerializers); + otherSupportedSerializers.add(defaultSerializer); + this.supportedSerializers = Set.copyOf(otherSupportedSerializers); + this.defaultSerializer = defaultSerializer; + this.value = identifier; + } + } + + enum Serializer { + GSON, JACKSON, JSONB; + public String toString() { + return this.name().toLowerCase(Locale.ROOT); + } + } + + @DataProvider Iterator supportedLibraries() { + return Arrays.stream(Library.values()).iterator(); + } + + @DataProvider Iterator librariesSupportingGson() { + return Arrays.stream(Library.values()) + .filter(library -> library.getSupportedSerializers().contains(Serializer.GSON)) + .iterator(); + } + + @Test public void arraysInRequestBody() { OpenAPI openAPI = TestUtils.createOpenAPI(); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOpenAPI(openAPI); RequestBody body1 = new RequestBody(); body1.setDescription("A list of ids"); - body1.setContent( - new Content() - .addMediaType( - "application/json", - new MediaType().schema(new ArraySchema().items(new StringSchema())))); - CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1, new HashSet(), null); + body1.setContent(new Content().addMediaType( + "application/json", + new MediaType().schema(new ArraySchema().items(new StringSchema())) + )); + CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1, new HashSet<>(), null); Assertions.assertEquals(codegenParameter1.description, "A list of ids"); Assertions.assertEquals(codegenParameter1.dataType, "List"); Assertions.assertEquals(codegenParameter1.baseType, "String"); RequestBody body2 = new RequestBody(); body2.setDescription("A list of list of values"); - body2.setContent( - new Content() - .addMediaType( - "application/json", - new MediaType() - .schema( - new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))))); - CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2, new HashSet(), null); + body2.setContent(new Content().addMediaType( + "application/json", + new MediaType().schema(new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))) + )); + CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2, new HashSet<>(), null); Assertions.assertEquals(codegenParameter2.description, "A list of list of values"); Assertions.assertEquals(codegenParameter2.dataType, "List>"); Assertions.assertEquals(codegenParameter2.baseType, "List"); @@ -140,7 +158,7 @@ public class JavaClientCodegenTest { point.addProperty("message", new StringSchema()); point.addProperty("x", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); point.addProperty("y", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); - CodegenParameter codegenParameter3 = codegen.fromRequestBody(body3, new HashSet(), null); + CodegenParameter codegenParameter3 = codegen.fromRequestBody(body3, new HashSet<>(), null); Assertions.assertEquals(codegenParameter3.description, "A list of points"); Assertions.assertEquals(codegenParameter3.dataType, "List"); Assertions.assertEquals(codegenParameter3.baseType, "Point"); @@ -239,7 +257,7 @@ public class JavaClientCodegenTest { codegen .additionalProperties() .put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.zzzzzzz.iiii.invoker"); - codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "JACKSON"); + codegen.additionalProperties().put(SERIALIZATION_LIBRARY, "JACKSON"); codegen.additionalProperties().put(CodegenConstants.LIBRARY, JavaClientCodegen.JERSEY2); codegen.processOpts(); @@ -257,65 +275,46 @@ public class JavaClientCodegenTest { Assertions.assertEquals( codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.zzzzzzz.iiii.invoker"); - Assertions.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_JACKSON); + Assertions.assertEquals(codegen.getSerializationLibrary(), SERIALIZATION_LIBRARY_JACKSON); } - @Test - public void testGeneratedAuthClassesJersey() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); + @Test public void testGeneratedAuthClassesJersey() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.JERSEY3) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) + .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - File output = Files.createTempDirectory("test").toFile(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.JERSEY3) - .setAdditionalProperties(properties) - .setInputSpec( - "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - - DefaultGenerator generator = new DefaultGenerator(); - - List files = generator.opts(clientOptInput).generate(); - - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java"); + assertThat(files).contains( + output.resolve("src/main/java/xyz/abcdef/auth/ApiKeyAuth.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/Authentication.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBasicAuth.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBearerAuth.java").toFile(), + output.resolve("src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java").toFile() + ); } - @Test - public void testImportMappingResult() throws IOException { - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testImportMappingResult() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .addTypeMapping("OffsetDateTime", "Instant") .addImportMapping("OffsetDateTime", "java.time.Instant") .setGeneratorName("java") .setInputSpec("src/test/resources/3_0/echo_api.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - DefaultGenerator generator = new DefaultGenerator(); - - List files = generator.opts(clientOptInput).generate(); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/QueryApi.java"), - "import java.time.Instant;"); + assertThat(output.resolve("src/main/java/org/openapitools/client/api/QueryApi.java")) + .content().contains("import java.time.Instant;"); } @Test - public void testSupportedSecuritySchemesJersey() throws Exception { + public void testSupportedSecuritySchemesJersey() { final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.additionalProperties().put(CodegenConstants.LIBRARY, JavaClientCodegen.JERSEY3); codegen.processOpts(); @@ -323,72 +322,56 @@ public class JavaClientCodegenTest { Assertions.assertTrue(codegen.getFeatureSet().getSecurityFeatures().contains(SecurityFeature.SignatureAuth)); } - @Test - public void testPackageNamesSetInvokerDerivedFromApi() { + @Test public void testPackageNamesSetInvokerDerivedFromApi() { final JavaClientCodegen codegen = new JavaClientCodegen(); - codegen - .additionalProperties() - .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); + codegen.processOpts(); - Assertions.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assertions.assertEquals( - codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), - "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assertions.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); - Assertions.assertEquals( - codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), - "xyz.yyyyy.zzzzzzz.aaaaa.api"); - Assertions.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.aaaaa"); - Assertions.assertEquals( - codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), - "xyz.yyyyy.zzzzzzz.aaaaa"); + assertThat(codegen) + .extracting(CodegenConfig::modelPackage, CodegenConfig::apiPackage, JavaClientCodegen::getInvokerPackage) + .containsExactly("xyz.yyyyy.zzzzzzz.mmmmm.model", "xyz.yyyyy.zzzzzzz.aaaaa.api", "xyz.yyyyy.zzzzzzz.aaaaa"); + assertThat(codegen.additionalProperties()).contains( + entry(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"), + entry(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"), + entry(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa") + ); } - @Test - public void testPackageNamesSetInvokerDerivedFromModel() { + @Test public void testPackageNamesSetInvokerDerivedFromModel() { final JavaClientCodegen codegen = new JavaClientCodegen(); - codegen - .additionalProperties() - .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.processOpts(); - Assertions.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assertions.assertEquals( - codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), - "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assertions.assertEquals(codegen.apiPackage(), "org.openapitools.client.api"); - Assertions.assertEquals( - codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), - "org.openapitools.client.api"); - Assertions.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.mmmmm"); - Assertions.assertEquals( - codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), - "xyz.yyyyy.zzzzzzz.mmmmm"); + assertThat(codegen) + .extracting(CodegenConfig::modelPackage, CodegenConfig::apiPackage, JavaClientCodegen::getInvokerPackage) + .containsExactly("xyz.yyyyy.zzzzzzz.mmmmm.model", "org.openapitools.client.api", "xyz.yyyyy.zzzzzzz.mmmmm"); + assertThat(codegen.additionalProperties()).contains( + entry(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"), + entry(CodegenConstants.API_PACKAGE, "org.openapitools.client.api"), + entry(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm") + ); } - @Test - public void testGetSchemaTypeWithComposedSchemaWithAllOf() { - final OpenAPI openAPI = - TestUtils.parseFlattenSpec("src/test/resources/2_0/composed-allof.yaml"); - final JavaClientCodegen codegen = new JavaClientCodegen(); - + @Test public void testGetSchemaTypeWithComposedSchemaWithAllOf() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/composed-allof.yaml"); Operation operation = openAPI.getPaths().get("/ping").getPost(); - CodegenOperation co = codegen.fromOperation("/ping", "POST", operation, null); - Assertions.assertEquals(co.allParams.size(), 1); - Assertions.assertEquals(co.allParams.get(0).baseType, "MessageEventCoreWithTimeListEntries"); + + CodegenOperation co = new JavaClientCodegen().fromOperation("/ping", "POST", operation, null); + + assertThat(co.allParams).hasSize(1) + .first().hasFieldOrPropertyWithValue("baseType", "MessageEventCoreWithTimeListEntries"); } - @Test - public void updateCodegenPropertyEnum() { + @Test public void updateCodegenPropertyEnum() { final JavaClientCodegen codegen = new JavaClientCodegen(); CodegenProperty array = codegenPropertyWithArrayOfIntegerValues(); codegen.updateCodegenPropertyEnum(array); - List> enumVars = - (List>) array.getItems().getAllowableValues().get("enumVars"); + var enumVars = (List>) array.getItems().getAllowableValues().get("enumVars"); Assertions.assertNotNull(enumVars); Map testedEnumVar = enumVars.get(0); Assertions.assertNotNull(testedEnumVar); @@ -396,19 +379,14 @@ public class JavaClientCodegenTest { Assertions.assertEquals(testedEnumVar.getOrDefault("value", ""), "1"); } - @Test - public void updateCodegenPropertyEnumWithCustomNames() { + @Test public void updateCodegenPropertyEnumWithCustomNames() { final JavaClientCodegen codegen = new JavaClientCodegen(); CodegenProperty array = codegenPropertyWithArrayOfIntegerValues(); - array - .getItems() - .setVendorExtensions( - Collections.singletonMap("x-enum-varnames", Collections.singletonList("ONE"))); + array.getItems().setVendorExtensions(Map.of("x-enum-varnames", Collections.singletonList("ONE"))); codegen.updateCodegenPropertyEnum(array); - List> enumVars = - (List>) array.getItems().getAllowableValues().get("enumVars"); + var enumVars = (List>) array.getItems().getAllowableValues().get("enumVars"); Assertions.assertNotNull(enumVars); Map testedEnumVar = enumVars.get(0); Assertions.assertNotNull(testedEnumVar); @@ -416,300 +394,217 @@ public class JavaClientCodegenTest { Assertions.assertEquals(testedEnumVar.getOrDefault("value", ""), "1"); } - @Test - public void testGeneratePing() throws Exception { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testGeneratePing() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.OKHTTP_GSON) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/ping.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - Assertions.assertEquals(files.size(), 40); - TestUtils.ensureContainsFile(files, output, ".gitignore"); - TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore"); - TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES"); - TestUtils.ensureContainsFile(files, output, ".openapi-generator/VERSION"); - TestUtils.ensureContainsFile(files, output, ".travis.yml"); - TestUtils.ensureContainsFile(files, output, "build.gradle"); - TestUtils.ensureContainsFile(files, output, "build.sbt"); - TestUtils.ensureContainsFile(files, output, "docs/DefaultApi.md"); - TestUtils.ensureContainsFile(files, output, "git_push.sh"); - TestUtils.ensureContainsFile(files, output, "gradle.properties"); - TestUtils.ensureContainsFile(files, output, "gradle/wrapper/gradle-wrapper.jar"); - TestUtils.ensureContainsFile(files, output, "gradle/wrapper/gradle-wrapper.properties"); - TestUtils.ensureContainsFile(files, output, "gradlew.bat"); - TestUtils.ensureContainsFile(files, output, "gradlew"); - TestUtils.ensureContainsFile(files, output, "pom.xml"); - TestUtils.ensureContainsFile(files, output, "README.md"); - TestUtils.ensureContainsFile(files, output, "settings.gradle"); - TestUtils.ensureContainsFile(files, output, "api/openapi.yaml"); - TestUtils.ensureContainsFile(files, output, "src/main/AndroidManifest.xml"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/api/DefaultApi.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiCallback.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiClient.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiException.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiResponse.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/ServerConfiguration.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ServerVariable.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/Configuration.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/GzipRequestInterceptor.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/JSON.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/Pair.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/ProgressRequestBody.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/ProgressResponseBody.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/StringUtil.java"); - TestUtils.ensureContainsFile(files, output, "src/test/java/xyz/abcdef/api/DefaultApiTest.java"); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "public class DefaultApi"); - - output.deleteOnExit(); + assertThat(files).hasSize(40).map(File::toPath).contains( + output.resolve(".gitignore"), + output.resolve(".openapi-generator-ignore"), + output.resolve(".openapi-generator/FILES"), + output.resolve(".openapi-generator/VERSION"), + output.resolve(".travis.yml"), + output.resolve("build.gradle"), + output.resolve("build.sbt"), + output.resolve("docs/DefaultApi.md"), + output.resolve("git_push.sh"), + output.resolve("gradle.properties"), + output.resolve("gradle/wrapper/gradle-wrapper.jar"), + output.resolve("gradle/wrapper/gradle-wrapper.properties"), + output.resolve("gradlew.bat"), + output.resolve("gradlew"), + output.resolve("pom.xml"), + output.resolve("README.md"), + output.resolve("settings.gradle"), + output.resolve("api/openapi.yaml"), + output.resolve("src/main/AndroidManifest.xml"), + output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java"), + output.resolve("src/main/java/xyz/abcdef/ApiCallback.java"), + output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), + output.resolve("src/main/java/xyz/abcdef/ApiException.java"), + output.resolve("src/main/java/xyz/abcdef/ApiResponse.java"), + output.resolve("src/main/java/xyz/abcdef/ServerVariable.java"), + output.resolve("src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"), + output.resolve("src/main/java/xyz/abcdef/ServerConfiguration.java"), + output.resolve("src/main/java/xyz/abcdef/auth/Authentication.java"), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"), + output.resolve("src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"), + output.resolve("src/main/java/xyz/abcdef/Configuration.java"), + output.resolve("src/main/java/xyz/abcdef/GzipRequestInterceptor.java"), + output.resolve("src/main/java/xyz/abcdef/JSON.java"), + output.resolve("src/main/java/xyz/abcdef/ProgressRequestBody.java"), + output.resolve("src/main/java/xyz/abcdef/Pair.java"), + output.resolve("src/main/java/xyz/abcdef/ProgressResponseBody.java"), + output.resolve("src/main/java/xyz/abcdef/StringUtil.java"), + output.resolve("src/test/java/xyz/abcdef/api/DefaultApiTest.java") + ); + assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content() + .contains("public class DefaultApi"); } - @Test - public void testGeneratePingSomeObj() throws Exception { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.MODEL_PACKAGE, "zz.yyyy.model.xxxx"); - properties.put(CodegenConstants.API_PACKAGE, "zz.yyyy.api.xxxx"); - properties.put(CodegenConstants.INVOKER_PACKAGE, "zz.yyyy.invoker.xxxx"); - properties.put(AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX, "is"); - - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testGeneratePingSomeObj(){ + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.OKHTTP_GSON) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "zz.yyyy.model.xxxx") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "zz.yyyy.api.xxxx") + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "zz.yyyy.invoker.xxxx") + .addAdditionalProperty(AbstractJavaCodegen.BOOLEAN_GETTER_PREFIX, "is") + .setLibrary(JavaClientCodegen.OKHTTP_GSON) + .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - Assertions.assertEquals(files.size(), 43); - TestUtils.ensureContainsFile(files, output, ".gitignore"); - TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore"); - TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES"); - TestUtils.ensureContainsFile(files, output, ".openapi-generator/VERSION"); - TestUtils.ensureContainsFile(files, output, ".travis.yml"); - TestUtils.ensureContainsFile(files, output, "build.gradle"); - TestUtils.ensureContainsFile(files, output, "build.sbt"); - TestUtils.ensureContainsFile(files, output, "docs/PingApi.md"); - TestUtils.ensureContainsFile(files, output, "docs/SomeObj.md"); - TestUtils.ensureContainsFile(files, output, "git_push.sh"); - TestUtils.ensureContainsFile(files, output, "gradle.properties"); - TestUtils.ensureContainsFile(files, output, "gradle/wrapper/gradle-wrapper.jar"); - TestUtils.ensureContainsFile(files, output, "gradle/wrapper/gradle-wrapper.properties"); - TestUtils.ensureContainsFile(files, output, "gradlew.bat"); - TestUtils.ensureContainsFile(files, output, "gradlew"); - TestUtils.ensureContainsFile(files, output, "pom.xml"); - TestUtils.ensureContainsFile(files, output, "README.md"); - TestUtils.ensureContainsFile(files, output, "settings.gradle"); - TestUtils.ensureContainsFile(files, output, "api/openapi.yaml"); - TestUtils.ensureContainsFile(files, output, "src/main/AndroidManifest.xml"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/api/xxxx/PingApi.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/JSON.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/Pair.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/model/xxxx/SomeObj.java"); - TestUtils.ensureContainsFile(files, output, "src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"); - TestUtils.ensureContainsFile( - files, output, "src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java"); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), - "public class SomeObj", - "Boolean isActive()"); - - output.deleteOnExit(); + assertThat(output.resolve("src/main/java/zz/yyyy/model/xxxx/SomeObj.java")).content() + .contains("public class SomeObj", "Boolean isActive()"); + assertThat(files).hasSize(43).map(File::toPath).contains( + output.resolve(".gitignore"), + output.resolve(".openapi-generator-ignore"), + output.resolve(".openapi-generator/FILES"), + output.resolve(".openapi-generator/VERSION"), + output.resolve(".travis.yml"), + output.resolve("build.gradle"), + output.resolve("build.sbt"), + output.resolve("docs/PingApi.md"), + output.resolve("docs/SomeObj.md"), + output.resolve("git_push.sh"), + output.resolve("gradle.properties"), + output.resolve("gradle/wrapper/gradle-wrapper.jar"), + output.resolve("gradle/wrapper/gradle-wrapper.properties"), + output.resolve("gradlew.bat"), + output.resolve("gradlew"), + output.resolve("pom.xml"), + output.resolve("README.md"), + output.resolve("settings.gradle"), + output.resolve("api/openapi.yaml"), + output.resolve("src/main/AndroidManifest.xml"), + output.resolve("src/main/java/zz/yyyy/api/xxxx/PingApi.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/JSON.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/Pair.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"), + output.resolve("src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"), + output.resolve("src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), + output.resolve("src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"), + output.resolve("src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java") + ); } - @Test - public void testJdkHttpClient() throws Exception { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testJdkHttpClient() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/ping.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - Assertions.assertEquals(files.size(), 32); + assertThat(files).hasSize(32); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "public class DefaultApi", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;", - "import java.net.http.HttpResponse;"); - - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), - "public class ApiClient", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;"); + assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content().contains( + "public class DefaultApi", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;", + "import java.net.http.HttpResponse;" + ); + assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content().contains( + "public class ApiClient", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;" + ); } - @Test - public void testJdkHttpClientWithUseBeanValidationEnabled() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_BEANVALIDATION, true); - properties.put(JavaClientCodegen.USE_JAKARTA_EE, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testJdkHttpClientWithUseBeanValidationEnabled() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_1/issue-17485.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.NATIVE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, true) + .addAdditionalProperty(JavaClientCodegen.USE_JAKARTA_EE, true) + .setInputSpec("src/test/resources/3_1/issue-17485.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/api/UserApi.java"), - "@Pattern", "import jakarta.validation.constraints.*"); + assertThat(output.resolve("src/main/java/xyz/abcdef/api/UserApi.java")).content() + .contains("@Pattern", "import jakarta.validation.constraints.*"); } - @Test - public void testJdkHttpClientWithAndWithoutDiscriminator() throws Exception { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model"); - properties.put(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker"); + @Test public void testJdkHttpClientWithAndWithoutDiscriminator() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.NATIVE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model") + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") + .setInputSpec("src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) - .setInputSpec( - "src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); - List files = generator.opts(clientOptInput).generate(); + List files = generator.opts(configurator.toClientOptInput()).generate(); - Assertions.assertEquals(files.size(), 153); + assertThat(files).hasSize(153); validateJavaSourceFiles(files); - - TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/model/Dog.java"), - "import xyz.abcdef.invoker.JSON;"); + assertThat(output.resolve("src/main/java/xyz/abcdef/model/Dog.java")).content() + .contains("import xyz.abcdef.invoker.JSON;"); } - @Test - public void testJdkHttpAsyncClient() throws Exception { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.ASYNC_NATIVE, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testJdkHttpAsyncClient() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.ASYNC_NATIVE, true) + .setLibrary(JavaClientCodegen.NATIVE) + .setInputSpec("src/test/resources/3_0/pingSomeObj.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + assertThat(files).hasSize(35); - Assertions.assertEquals(files.size(), 35); validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/PingApi.java"); - TestUtils.assertFileContains(defaultApi, - "public class PingApi", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;", - "import java.net.http.HttpResponse;", - "import java.util.concurrent.CompletableFuture;"); - - Path apiClient = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"); - TestUtils.assertFileContains(apiClient, - "public class ApiClient", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;"); + assertThat(output.resolve("src/main/java/xyz/abcdef/api/PingApi.java")).content().contains( + "public class PingApi", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;", + "import java.net.http.HttpResponse;", + "import java.util.concurrent.CompletableFuture;" + ); + assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content().contains( + "public class ApiClient", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;" + ); } @Test @@ -764,19 +659,14 @@ public class JavaClientCodegenTest { assertEquals(postScopes.size(), 2, "POST scopes don't match. actual:" + postScopes); } - @Test - public void testAuthorizationScopeValues_Issue6733() throws IOException { - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testAuthorizationScopeValues_Issue6733() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTEASY) .setValidateSpec(false) .setInputSpec("src/test/resources/3_0/regression-6734.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -786,27 +676,20 @@ public class JavaClientCodegenTest { // tests if NPE will crash generation when path in yaml arent provided generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); generator.setGenerateMetadata(false); - List files = generator.opts(clientOptInput).generate(); + List files = generator.opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - Assertions.assertEquals(files.size(), 1); - files.forEach(File::deleteOnExit); } - @Test - public void testTypedAndNonTypedComposedSchemaGeneration_3_1() throws IOException { - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testTypedAndNonTypedComposedSchemaGeneration_3_1() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTEASY) .setValidateSpec(false) .setInputSpec("src/test/resources/3_1/composed-schemas-with-and-without-type.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -815,27 +698,20 @@ public class JavaClientCodegenTest { generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); generator.setGenerateMetadata(false); - List files = generator.opts(clientOptInput).generate(); + List files = generator.opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - Assertions.assertEquals(files.size(), 9); - files.forEach(File::deleteOnExit); } - @Test - public void testMultiPartSpecifiesFileName_Issue17367() throws IOException { - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testMultiPartSpecifiesFileName_Issue17367() throws IOException { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTEASY) .setValidateSpec(false) .setInputSpec("src/test/resources/3_0/issue-17367.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -844,79 +720,64 @@ public class JavaClientCodegenTest { generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true"); generator.setGenerateMetadata(false); - List files = generator.opts(clientOptInput).generate(); - try { - validateJavaSourceFiles(files); - File apiClient = files.stream() - .filter(f -> f.getName().equals("ApiClient.java")) - .findFirst() - .orElseThrow(() -> new AssertionError( - "ApiClient.java not found")); - - Stream contents = Arrays.stream(Files.readString(apiClient.toPath(), - StandardCharsets.UTF_8).split("\n")); - - // https://docs.jboss.org/resteasy/docs/6.2.5.Final/javadocs/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataOutput.html#addFormData(java.lang.String,java.lang.Object,jakarta.ws.rs.core.MediaType,java.lang.String) - assertTrue(contents.anyMatch(l -> l.matches( - ".*multipart\\.addFormData\\(param.getKey\\(\\),\\s*" + - "new\\s+FileInputStream\\(file\\),\\s*" + - "MediaType\\.APPLICATION_OCTET_STREAM_TYPE,\\s*" + - "file.getName\\(\\)\\);.*"))); - } finally { - files.forEach(File::deleteOnExit); - } + List files = generator.opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + File apiClient = files.stream() + .filter(f -> f.getName().equals("ApiClient.java")) + .findFirst() + .orElseThrow(() -> new AssertionError("ApiClient.java not found")); + var contents = Arrays.stream(Files.readString(apiClient.toPath(), StandardCharsets.UTF_8).split("\n")); + // https://docs.jboss.org/resteasy/docs/6.2.5.Final/javadocs/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataOutput.html#addFormData(java.lang.String,java.lang.Object,jakarta.ws.rs.core.MediaType,java.lang.String) + assertTrue(contents.anyMatch(l -> l.matches( + ".*multipart\\.addFormData\\(param.getKey\\(\\),\\s*" + + "new\\s+FileInputStream\\(file\\),\\s*" + + "MediaType\\.APPLICATION_OCTET_STREAM_TYPE,\\s*" + + "file.getName\\(\\)\\);.*"))); } - @Test - public void testAuthorizationsMethodsSizeWhenFiltered() { + @Test public void testAuthorizationsMethodsSizeWhenFiltered() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue4584.yaml"); - + final ClientOptInput clientOptInput = new ClientOptInput().openAPI(openAPI).config(new JavaClientCodegen()); final DefaultGenerator defaultGenerator = new DefaultGenerator(); - - final ClientOptInput clientOptInput = new ClientOptInput(); - clientOptInput.openAPI(openAPI); - clientOptInput.config(new JavaClientCodegen()); - defaultGenerator.opts(clientOptInput); - final List codegenOperations = - defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); + + final List codegenOperations = defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); - final CodegenOperation getCodegenOperation = - codegenOperations.stream() - .filter(it -> it.httpMethod.equals("GET")) - .collect(Collectors.toList()) - .get(0); + final CodegenOperation getCodegenOperation = codegenOperations.stream() + .filter(it -> it.httpMethod.equals("GET")) + .collect(Collectors.toList()) + .get(0); assertTrue(getCodegenOperation.hasAuthMethods); assertEquals(getCodegenOperation.authMethods.size(), 2); } - @Test - public void testFreeFormObjects() { + @Test public void testFreeFormObjects() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue796.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); - Schema test1 = openAPI.getComponents().getSchemas().get("MapTest1"); + Schema test1 = openAPI.getComponents().getSchemas().get("MapTest1"); codegen.setOpenAPI(openAPI); CodegenModel cm1 = codegen.fromModel("MapTest1", test1); Assertions.assertEquals(cm1.getDataType(), "Map"); Assertions.assertEquals(cm1.getParent(), "HashMap"); Assertions.assertEquals(cm1.getClassname(), "MapTest1"); - Schema test2 = openAPI.getComponents().getSchemas().get("MapTest2"); + Schema test2 = openAPI.getComponents().getSchemas().get("MapTest2"); codegen.setOpenAPI(openAPI); CodegenModel cm2 = codegen.fromModel("MapTest2", test2); Assertions.assertEquals(cm2.getDataType(), "Map"); Assertions.assertEquals(cm2.getParent(), "HashMap"); Assertions.assertEquals(cm2.getClassname(), "MapTest2"); - Schema test3 = openAPI.getComponents().getSchemas().get("MapTest3"); + Schema test3 = openAPI.getComponents().getSchemas().get("MapTest3"); codegen.setOpenAPI(openAPI); CodegenModel cm3 = codegen.fromModel("MapTest3", test3); Assertions.assertEquals(cm3.getDataType(), "Map"); Assertions.assertEquals(cm3.getParent(), "HashMap"); Assertions.assertEquals(cm3.getClassname(), "MapTest3"); - Schema other = openAPI.getComponents().getSchemas().get("OtherObj"); + Schema other = openAPI.getComponents().getSchemas().get("OtherObj"); codegen.setOpenAPI(openAPI); CodegenModel cm = codegen.fromModel("OtherObj", other); Assertions.assertEquals(cm.getDataType(), "Object"); @@ -926,55 +787,32 @@ public class JavaClientCodegenTest { /** * See https://github.com/OpenAPITools/openapi-generator/issues/3589 */ - @Test - public void testSchemaMapping() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - Map schemaMappings = new HashMap<>(); - schemaMappings.put("TypeAlias", "foo.bar.TypeAlias"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator() + @Test public void testSchemaMapping() throws IOException { + final Path output = newTempFolder(); + final ClientOptInput clientOptInput = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTEASY) - .setAdditionalProperties(properties) - .setSchemaMappings(schemaMappings) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) + .setSchemaMappings(Map.of("TypeAlias", "foo.bar.TypeAlias")) .setGenerateAliasAsModel(true) .setInputSpec("src/test/resources/3_0/type-alias.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - Assertions.assertEquals( - clientOptInput.getConfig().schemaMapping().get("TypeAlias"), "foo.bar.TypeAlias"); + .setOutputDir(output.toString().replace("\\", "/")) + .toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); - generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "false"); - generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); generator.setGenerateMetadata(false); List files = generator.opts(clientOptInput).generate(); - files.forEach(File::deleteOnExit); validateJavaSourceFiles(files); + Assertions.assertEquals(clientOptInput.getConfig().schemaMapping().get("TypeAlias"), "foo.bar.TypeAlias"); + assertThat(files).hasSize(1) + .contains(output.resolve("src/main/java/org/openapitools/client/model/ParentType.java").toFile()); - Assertions.assertEquals(files.size(), 1); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/model/ParentType.java"); - - String parentTypeContents = ""; - try { - File file = - files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get(); - parentTypeContents = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); - } catch (IOException ignored) { - - } + File file = files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get(); + String parentTypeContents = Files.readString(file.toPath()); final Pattern FIELD_PATTERN = Pattern.compile(".* private (.*?) typeAlias;.*", Pattern.DOTALL); Matcher fieldMatcher = FIELD_PATTERN.matcher(parentTypeContents); @@ -985,37 +823,28 @@ public class JavaClientCodegenTest { Assertions.assertEquals(fieldMatcher.group(1), "foo.bar.TypeAlias"); } - @Test - public void testBearerAuth() { - final OpenAPI openAPI = - TestUtils.parseFlattenSpec("src/test/resources/3_0/pingBearerAuth.yaml"); - JavaClientCodegen codegen = new JavaClientCodegen(); + @Test public void testBearerAuth() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/pingBearerAuth.yaml"); - List security = codegen.fromSecurity(openAPI.getComponents().getSecuritySchemes()); - Assertions.assertEquals(security.size(), 1); - Assertions.assertEquals(security.get(0).isBasic, Boolean.TRUE); - Assertions.assertEquals(security.get(0).isBasicBasic, Boolean.FALSE); - Assertions.assertEquals(security.get(0).isBasicBearer, Boolean.TRUE); + List security = new JavaClientCodegen().fromSecurity(openAPI.getComponents().getSecuritySchemes()); + + assertThat(security).hasSize(1) + .first() + .hasFieldOrPropertyWithValue("isBasic", Boolean.TRUE) + .hasFieldOrPropertyWithValue("isBasicBasic", Boolean.FALSE) + .hasFieldOrPropertyWithValue("isBasicBearer", Boolean.TRUE); } - @Test - public void testVertXAuthInfoWithHyphenSeparatedSecurityScheme() throws Exception { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testVertXAuthInfoWithHyphenSeparatedSecurityScheme() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.VERTX) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/ping-with-hyphen-separated-security-scheme.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); // Test that hyphen-separated security scheme names does not // break the Java VertX client code generation @@ -1023,8 +852,8 @@ public class JavaClientCodegenTest { // Test that the name was correctly transformed to camelCase // starting with an uppercase letter - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), + assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content() + .contains( "public static class AuthInfo {", "public void addHyphenatedNameTestAuthentication(String bearerToken) {", "public static AuthInfo forHyphenatedNameTestAuthentication(String bearerToken) {" @@ -1034,9 +863,7 @@ public class JavaClientCodegenTest { private CodegenProperty codegenPropertyWithArrayOfIntegerValues() { CodegenProperty array = new CodegenProperty(); final CodegenProperty items = new CodegenProperty(); - final HashMap allowableValues = new HashMap<>(); - allowableValues.put("values", Collections.singletonList(1)); - items.setAllowableValues(allowableValues); + items.setAllowableValues(new HashMap<>(Map.of("values", Collections.singletonList(1)))); items.dataType = "Integer"; array.setItems(items); array.dataType = "Array"; @@ -1078,7 +905,7 @@ public class JavaClientCodegenTest { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/any_type.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); - Schema test1 = openAPI.getComponents().getSchemas().get("AnyValueModel"); + Schema test1 = openAPI.getComponents().getSchemas().get("AnyValueModel"); codegen.setOpenAPI(openAPI); CodegenModel cm1 = codegen.fromModel("AnyValueModel", test1); Assertions.assertEquals(cm1.getClassname(), "AnyValueModel"); @@ -1109,7 +936,7 @@ public class JavaClientCodegenTest { Assertions.assertFalse(property3.isFreeFormObject); Assertions.assertTrue(property3.isAnyType); - Schema test2 = openAPI.getComponents().getSchemas().get("AnyValueModelInline"); + Schema test2 = openAPI.getComponents().getSchemas().get("AnyValueModelInline"); codegen.setOpenAPI(openAPI); CodegenModel cm2 = codegen.fromModel("AnyValueModelInline", test2); Assertions.assertEquals(cm2.getClassname(), "AnyValueModelInline"); @@ -1219,35 +1046,20 @@ public class JavaClientCodegenTest { * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test - @Ignore - public void testRestTemplateFormMultipart() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test(enabled = false) public void testRestTemplateFormMultipart() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, - // multiple files + assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() + .contains( "multipartArrayWithHttpInfo(List files)", "formParams.addAll(\"files\"," + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", @@ -1258,7 +1070,8 @@ public class JavaClientCodegenTest { // single file "multipartSingleWithHttpInfo(File file)", - "formParams.add(\"file\", new FileSystemResource(file));"); + "formParams.add(\"file\", new FileSystemResource(file));" + ); } /** @@ -1268,34 +1081,20 @@ public class JavaClientCodegenTest { * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test - @Ignore - public void testWebClientFormMultipart() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test(enabled = false) public void testWebClientFormMultipart() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, + assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() + .contains( // multiple files "multipartArray(List files)", "formParams.addAll(\"files\"," @@ -1307,26 +1106,20 @@ public class JavaClientCodegenTest { // single file "multipartSingle(File file)", - "formParams.add(\"file\", new FileSystemResource(file));"); + "formParams.add(\"file\", new FileSystemResource(file));" + ); } @Test - public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.WEBCLIENT_BLOCKING_OPERATIONS, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) - .setInputSpec( - "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.WEBCLIENT_BLOCKING_OPERATIONS, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.toString().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(configurator.toClientOptInput()).generate().stream() @@ -1347,37 +1140,25 @@ public class JavaClientCodegenTest { "List"); // explicit 'x-webclient-blocking: true' which overrides global config } - @Test - public void testAllowModelWithNoProperties() throws Exception { - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testAllowModelWithNoProperties() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.OKHTTP_GSON) .setInputSpec("src/test/resources/2_0/emptyBaseModel.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - Assertions.assertEquals(files.size(), 49); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/model/RealCommand.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/model/Command.java"); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/RealCommand.java"), - "class RealCommand {"); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/Command.java"), - "class Command {"); - - output.deleteOnExit(); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/RealCommand.java")) + .content().contains("class RealCommand {"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Command.java")) + .content().contains("class Command {"); + assertThat(files).hasSize(49).contains( + output.resolve("src/main/java/org/openapitools/client/model/RealCommand.java").toFile(), + output.resolve("src/main/java/org/openapitools/client/model/Command.java").toFile() + ); } /** @@ -1387,103 +1168,83 @@ public class JavaClientCodegenTest { * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test - @Ignore - public void testRestTemplateWithUseAbstractionForFiles() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test(enabled = false) public void testRestTemplateWithUseAbstractionForFiles() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); + assertThat(output.resolve("/src/main/java/xyz/abcdef/api/MultipartApi.java")).content().contains( + // multiple files + "multipartArray(java.util.Collection files)", + "multipartArrayWithHttpInfo(java.util.Collection" + + " files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, - // multiple files - "multipartArray(java.util.Collection files)", - "multipartArrayWithHttpInfo(java.util.Collection" - + " files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + // mixed + "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", + "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker" + + " marker)", + "formParams.add(\"file\", file);", - // mixed - "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", - "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker" - + " marker)", - "formParams.add(\"file\", file);", - - // single file - "multipartSingle(org.springframework.core.io.Resource file)", - "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", - "formParams.add(\"file\", file);"); + // single file + "multipartSingle(org.springframework.core.io.Resource file)", + "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", + "formParams.add(\"file\", file);" + ); } - @Test - void testNotDuplicateOauth2FlowsScopes() { + @Test void testNotDuplicateOauth2FlowsScopes() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7614.yaml"); - - final ClientOptInput clientOptInput = new ClientOptInput() - .openAPI(openAPI) - .config(new JavaClientCodegen()); - + final ClientOptInput clientOptInput = new ClientOptInput().openAPI(openAPI).config(new JavaClientCodegen()); final DefaultGenerator defaultGenerator = new DefaultGenerator(); defaultGenerator.opts(clientOptInput); final Map> paths = defaultGenerator.processPaths(openAPI.getPaths()); - final List codegenOperations = paths.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); - final CodegenOperation getWithBasicAuthAndOauth = - getByOperationId(codegenOperations, "getWithBasicAuthAndOauth"); + final List codegenOperations = paths.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); + final CodegenOperation getWithBasicAuthAndOauth = getByOperationId(codegenOperations, "getWithBasicAuthAndOauth"); assertEquals(getWithBasicAuthAndOauth.authMethods.size(), 3); assertEquals(getWithBasicAuthAndOauth.authMethods.get(0).name, "basic_auth"); + final Map passwordFlowScope = getWithBasicAuthAndOauth.authMethods.get(1).scopes.get(0); assertEquals(passwordFlowScope.get("scope"), "something:create"); assertEquals(passwordFlowScope.get("description"), "create from password flow"); + final Map clientCredentialsFlow = getWithBasicAuthAndOauth.authMethods.get(2).scopes.get(0); assertEquals(clientCredentialsFlow.get("scope"), "something:create"); assertEquals(clientCredentialsFlow.get("description"), "create from client credentials flow"); - - final CodegenOperation getWithOauthAuth = - getByOperationId(codegenOperations, "getWithOauthAuth"); + + final CodegenOperation getWithOauthAuth = getByOperationId(codegenOperations, "getWithOauthAuth"); assertEquals(getWithOauthAuth.authMethods.size(), 2); + final Map passwordFlow = getWithOauthAuth.authMethods.get(0).scopes.get(0); assertEquals(passwordFlow.get("scope"), "something:create"); assertEquals(passwordFlow.get("description"), "create from password flow"); final Map clientCredentialsCreateFlow = getWithOauthAuth.authMethods.get(1).scopes.get(0); assertEquals(clientCredentialsCreateFlow.get("scope"), "something:create"); - assertEquals( - clientCredentialsCreateFlow.get("description"), "create from client credentials flow"); + assertEquals(clientCredentialsCreateFlow.get("description"), "create from client credentials flow"); final Map clientCredentialsProcessFlow = getWithOauthAuth.authMethods.get(1).scopes.get(1); assertEquals(clientCredentialsProcessFlow.get("scope"), "something:process"); - assertEquals( - clientCredentialsProcessFlow.get("description"), "process from client credentials flow"); + assertEquals(clientCredentialsProcessFlow.get("description"), "process from client credentials flow"); } private CodegenOperation getByOperationId(List codegenOperations, String operationId) { return getByCriteria(codegenOperations, (co) -> co.operationId.equals(operationId)) - .orElseThrow( - () -> - new IllegalStateException( - String.format( - Locale.ROOT, "Operation with id [%s] does not exist", operationId))); + .orElseThrow( + () -> new IllegalStateException( + String.format(Locale.ROOT, "Operation with id [%s] does not exist", operationId) + ) + ); } private Optional getByCriteria(List codegenOperations, Predicate filter) { @@ -1492,39 +1253,28 @@ public class JavaClientCodegenTest { .findFirst(); } - @Test - public void testCustomMethodParamsAreCamelizedWhenUsingFeign() throws IOException { - - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testCustomMethodParamsAreCamelizedWhenUsingFeign() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") - .setLibrary(JavaClientCodegen.FEIGN) + .setLibrary(FEIGN) .setInputSpec("src/test/resources/3_0/issue_7791.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); List files = generator.opts(clientOptInput).generate(); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/api/DefaultApi.java"); - validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "@RequestLine(\"POST /events/{eventId}:undelete\")"); - TestUtils.assertFileNotContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "event_id"); - - // baseName is kept for form parameters - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "@Param(\"some_file\") File someFile"); - - output.deleteOnExit(); + var defaultApiFile = output.resolve("src/main/java/org/openapitools/client/api/DefaultApi.java"); + assertThat(files).contains(defaultApiFile.toFile()); + assertThat(defaultApiFile).content() + .doesNotContain("event_id") + .contains( + "@RequestLine(\"POST /events/{eventId}:undelete\")", + // baseName is kept for form parameters + "@Param(\"some_file\") File someFile" + ); } /** @@ -1534,34 +1284,21 @@ public class JavaClientCodegenTest { * We will contact the contributor of the following test to see if the fix will break their use cases and * how we can fix it accordingly. */ - @Test - @Ignore - public void testWebClientWithUseAbstractionForFiles() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test(enabled = false) public void testWebClientWithUseAbstractionForFiles() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, + assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() + .contains( // multiple files "multipartArray(java.util.Collection files)", "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", @@ -1573,351 +1310,192 @@ public class JavaClientCodegenTest { // single file "multipartSingle(org.springframework.core.io.AbstractResource file)", - "formParams.add(\"file\", file);"); + "formParams.add(\"file\", file);" + ); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/8352 */ @Test - public void testRestTemplateWithFreeFormInQueryParameters() throws IOException { - final Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - final File output = Files.createTempDirectory("test") - .toFile(); - output.deleteOnExit(); - + public void testRestTemplateWithFreeFormInQueryParameters() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/issue8352.yaml") - .setOutputDir(output.getAbsolutePath() - .replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final DefaultGenerator generator = new DefaultGenerator(); - final List files = generator.opts(configurator.toClientOptInput()) - .generate(); - files.forEach(File::deleteOnExit); + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - final Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"); - TestUtils.assertFileContains(defaultApi, "value instanceof Map"); + assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content() + .contains("value instanceof Map"); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/8352 */ - @Test - public void testWebClientWithFreeFormInQueryParameters() throws IOException { - final Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - final File output = Files.createTempDirectory("test") - .toFile(); - output.deleteOnExit(); - + @Test public void testWebClientWithFreeFormInQueryParameters() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/issue8352.yaml") - .setOutputDir(output.getAbsolutePath() - .replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final DefaultGenerator generator = new DefaultGenerator(); - final List files = generator.opts(configurator.toClientOptInput()) - .generate(); - files.forEach(File::deleteOnExit); + final List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - final Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"); - TestUtils.assertFileContains(defaultApi, "value instanceof Map"); + assertThat(output.resolve("src/main/java/xyz/abcdef/ApiClient.java")).content() + .contains("value instanceof Map"); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/11242 */ - @Test - public void testNativeClientWhiteSpacePathParamEncoding() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testNativeClientWhiteSpacePathParamEncoding() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/issue11242.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - Assertions.assertEquals(files.size(), 35); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), - "public static String urlEncode(String s) { return URLEncoder.encode(s," - + " UTF_8).replaceAll(\"\\\\+\", \"%20\"); }"); + assertThat(files).hasSize(35); + TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), + "public static String urlEncode(String s) { return URLEncoder.encode(s," + + " UTF_8).replaceAll(\"\\\\+\", \"%20\"); }" + ); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/4808 */ - @Test - public void testNativeClientExplodedQueryParamObject() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testNativeClientExplodedQueryParamObject() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/issue4808.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - Assertions.assertEquals(files.size(), 38); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\"," - + " queryObject.getSince()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\"," - + " queryObject.getSinceBuild()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\"," - + " queryObject.getMaxBuilds()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\"," - + " queryObject.getMaxWaitSecs()));"); + assertThat(files).hasSize(38); + assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content() + .contains( + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\", queryObject.getSince()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\", queryObject.getSinceBuild()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\", queryObject.getMaxBuilds()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\", queryObject.getMaxWaitSecs()));" + ); } - @Test - public void testExtraAnnotationsNative() throws IOException { - testExtraAnnotations(JavaClientCodegen.NATIVE); - } - - @Test - public void testExtraAnnotationsJersey2() throws IOException { - testExtraAnnotations(JavaClientCodegen.JERSEY2); - } - - @Test - public void testExtraAnnotationsJersey3() throws IOException { - testExtraAnnotations(JavaClientCodegen.JERSEY3); - } - - @Test - public void testExtraAnnotationsMicroprofile() throws IOException { - testExtraAnnotations(JavaClientCodegen.MICROPROFILE); - } - - @Test - public void testExtraAnnotationsOKHttpGSON() throws IOException { - testExtraAnnotations(JavaClientCodegen.OKHTTP_GSON); - } - - @Test - public void testExtraAnnotationsVertx() throws IOException { - testExtraAnnotations(JavaClientCodegen.VERTX); - } - - @Test - public void testExtraAnnotationsFeign() throws IOException { - testExtraAnnotations(JavaClientCodegen.FEIGN); - } - - @Test - public void testExtraAnnotationsRetrofit2() throws IOException { - testExtraAnnotations(JavaClientCodegen.RETROFIT_2); - } - - @Test - public void testExtraAnnotationsRestTemplate() throws IOException { - testExtraAnnotations(JavaClientCodegen.RESTTEMPLATE); - } - - @Test - public void testExtraAnnotationsWebClient() throws IOException { - testExtraAnnotations(JavaClientCodegen.WEBCLIENT); - } - - @Test - public void testExtraAnnotationsRestEasy() throws IOException { - testExtraAnnotations(JavaClientCodegen.RESTEASY); - } - - @Test - public void testExtraAnnotationsGoogleApiClient() throws IOException { - testExtraAnnotations(JavaClientCodegen.GOOGLE_API_CLIENT); - } - - @Test - public void testExtraAnnotationsRestAssured() throws IOException { - testExtraAnnotations(JavaClientCodegen.REST_ASSURED); - } - - @Test - public void testExtraAnnotationsApache() throws IOException { - testExtraAnnotations(JavaClientCodegen.APACHE); - } - - @Test - public void testDefaultMicroprofileRestClientVersion() throws Exception { - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testDefaultMicroprofileRestClientVersion() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.MICROPROFILE) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - TestUtils.ensureContainsFile(files, output, "pom.xml"); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "2.0"); - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "1.2.1"); - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "1.8"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import javax."); - - output.deleteOnExit(); + assertThat(files).contains(output.resolve("pom.xml").toFile()); + assertThat(output.resolve("src/main/java/org/openapitools/client/api/PetApi.java")).content() + .contains("import javax."); + assertThat(output.resolve("pom.xml")).content() + .contains( + "2.0", + "1.2.1", + "1.8" + ); } - @Test - public void testMicroprofileRestClientVersion_1_4_1() throws Exception { - Map properties = new HashMap<>(); - properties.put(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "1.4.1"); - - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testMicroprofileRestClientVersion_1_4_1() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "1.4.1")) .setGeneratorName("java") .setLibrary(JavaClientCodegen.MICROPROFILE) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - TestUtils.ensureContainsFile(files, output, "pom.xml"); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/pom.xml"), - "1.4.1"); - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "1.2.1"); - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "1.8"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import javax."); - - output.deleteOnExit(); + assertThat(files).contains(output.resolve("pom.xml").toFile()); + assertThat(output.resolve("src/main/java/org/openapitools/client/api/PetApi.java")).content() + .contains("import javax."); + assertThat(output.resolve("pom.xml")).content() + .contains( + "1.4.1", + "1.2.1", + "1.8" + ); } @Test( - expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = - "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect." - + " Supported versions are 1.4.1, 2.0, 3.0") - public void testMicroprofileRestClientIncorrectVersion() throws Exception { - Map properties = new HashMap<>(); - properties.put(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "incorrectVersion"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = + "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect." + + " Supported versions are 1.4.1, 2.0, 3.0" + ) + public void testMicroprofileRestClientIncorrectVersion() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "incorrectVersion")) .setGeneratorName("java") .setLibrary(JavaClientCodegen.MICROPROFILE) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput).generate(); + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + fail("Expected an exception that did not occur"); } - @Test - public void testMicroprofileRestClientVersion_3_0() throws Exception { - Map properties = new HashMap<>(); - properties.put(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0"); - - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testMicroprofileRestClientVersion_3_0() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) .setGeneratorName("java") .setLibrary(JavaClientCodegen.MICROPROFILE) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - TestUtils.ensureContainsFile(files, output, "pom.xml"); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "3.0"); - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "3.0.4"); - TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), - "11"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import jakarta."); - - output.deleteOnExit(); + assertThat(files).contains(output.resolve("pom.xml").toFile()); + assertThat(output.resolve("src/main/java/org/openapitools/client/api/PetApi.java")).content() + .contains("import jakarta."); + assertThat(output.resolve("pom.xml")).content() + .contains( + "3.0", + "3.0.4", + "11" + ); } - @Test - public void testMicroprofileGenerateCorrectJsonbCreator_issue12622() throws Exception { - Map properties = new HashMap<>(); - properties.put(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testMicroprofileGenerateCorrectJsonbCreator_issue12622() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) .setGeneratorName("java") .setLibrary(JavaClientCodegen.MICROPROFILE) .setInputSpec("src/test/resources/bugs/issue_12622.json") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - Map files = generator.opts(clientOptInput).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate() + .stream().collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("Foo.java")) .assertConstructor("String", "Integer") @@ -1932,27 +1510,17 @@ public class JavaClientCodegenTest { .containsWithNameAndAttributes("JsonbProperty", ImmutableMap.of("value", "\"c\"")); } - @Test - public void testJavaClientDefaultValues_issueNoNumber() throws Exception { - Map properties = new HashMap<>(); - properties.put(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0"); + @Test public void testJavaClientDefaultValues_issueNoNumber() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setAdditionalProperties(Map.of(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "3.0")) + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setOutputDir(output.toString().replace("\\", "/")) + .setInputSpec("src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml"); - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setAdditionalProperties(properties) - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setInputSpec( - "src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - Map files = generator.opts(clientOptInput).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate() + .stream().collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("DefaultValuesType.java")) .hasProperty("stringDefault") @@ -1965,24 +1533,16 @@ public class JavaClientCodegenTest { .asString().endsWith("= new ArrayList<>();"); } - @Test - public void testWebClientJsonCreatorWithNullable_issue12790() throws Exception { - Map properties = new HashMap<>(); - properties.put(AbstractJavaCodegen.OPENAPI_NULLABLE, "true"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testWebClientJsonCreatorWithNullable_issue12790() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(AbstractJavaCodegen.OPENAPI_NULLABLE, "true")) .setGeneratorName("java") .setLibrary(JavaClientCodegen.WEBCLIENT) .setInputSpec("src/test/resources/bugs/issue_12790.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - Map files = generator.opts(clientOptInput).generate().stream() + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("TestObject.java")) @@ -1994,87 +1554,58 @@ public class JavaClientCodegenTest { "this.notNullableProperty = notNullableProperty;"); } - @Test - public void testRestTemplateResponseTypeWithUseAbstractionForFiles() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestTemplateResponseTypeWithUseAbstractionForFiles() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/ResourceApi.java"); - TestUtils.assertFileContains( - defaultApi, + assertThat(output.resolve("src/main/java/xyz/abcdef/api/ResourceApi.java")).content() + .contains( "org.springframework.core.io.Resource resourceInResponse()", "ResponseEntity resourceInResponseWithHttpInfo()", "ParameterizedTypeReference localReturnType = new" - + " ParameterizedTypeReference()"); + + " ParameterizedTypeReference()" + ); } - public void testExtraAnnotations(String library) throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - String outputPath = output.getAbsolutePath().replace('\\', '/'); - - Map properties = new HashMap<>(); - properties.put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); - + @Test(dataProvider = "supportedLibraries") void testExtraAnnotations(Library library) { + final Path output = newTempFolder(); + final String outputPath = output.toString().replace('\\', '/'); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") - .setLibrary(library) - .setAdditionalProperties(properties) + .setLibrary(library.value) + .setAdditionalProperties(Map.of(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true")) .setInputSpec("src/test/resources/3_0/issue_11772.yml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); + .setOutputDir(outputPath); + final DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); - generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "false"); - generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); - generator.opts(clientOptInput).generate(); + generator.opts(configurator.toClientOptInput()).generate(); - TestUtils.assertExtraAnnotationFiles( - outputPath + "/src/main/java/org/openapitools/client/model"); + TestUtils.assertExtraAnnotationFiles(outputPath + "/src/main/java/org/openapitools/client/model"); } /** * See https://github.com/OpenAPITools/openapi-generator/issues/11340 */ - @Test - public void testReferencedHeader2() throws Exception { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - Map additionalProperties = new HashMap<>(); - additionalProperties.put(BeanValidationFeatures.USE_BEANVALIDATION, "true"); + @Test public void testReferencedHeader2() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") - .setAdditionalProperties(additionalProperties) + .setAdditionalProperties(Map.of(BeanValidationFeatures.USE_BEANVALIDATION, "true")) .setInputSpec("src/test/resources/3_0/issue-11340.yaml") - .setOutputDir(output.getAbsolutePath() - .replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - - Map files = generator.opts(clientOptInput).generate().stream() + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("DefaultApi.java")) @@ -2088,45 +1619,32 @@ public class JavaClientCodegenTest { .containsWithName("NotNull"); } - @Test - public void testReturnTypeMapping() throws IOException { - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testReturnTypeMapping() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setInputSpec("src/test/resources/3_0/issue14525.yaml") .addTypeMapping("array", "Stack") .addImportMapping("Stack", "java.util.Stack") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput).generate(); + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "import java.util.Stack;"); + assertThat(output.resolve("src/main/java/org/openapitools/client/api/DefaultApi.java")).content() + .contains("import java.util.Stack;"); } @Test - public void testNativeClientExplodedQueryParamWithArrayProperty() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + public void testNativeClientExplodedQueryParamWithArrayProperty() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/exploded-query-param-array.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - generator.opts(clientOptInput).generate(); + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); TestUtils.assertFileContains( Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), @@ -2134,211 +1652,133 @@ public class JavaClientCodegenTest { + " queryObject.getValues()));"); } - @Test - public void testJdkHttpClientWithAndWithoutParentExtension() throws Exception { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model"); - properties.put(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testJdkHttpClientWithAndWithoutParentExtension() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - // use default `okhttp-gson` - //.setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/allOf_extension_parent.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + // use default `okhttp-gson` + //.setLibrary(JavaClientCodegen.NATIVE) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(CodegenConstants.MODEL_PACKAGE, "xyz.abcdef.model") + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") + .setInputSpec("src/test/resources/3_0/allOf_extension_parent.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); - List files = generator.opts(clientOptInput).generate(); + List files = generator.opts(configurator.toClientOptInput()).generate(); - Assertions.assertEquals(files.size(), 27); validateJavaSourceFiles(files); - - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/model/Child.java"), - "public class Child extends Person {"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/model/Adult.java"), - "public class Adult extends Person {"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/model/AnotherChild.java"), - "public class AnotherChild {"); + assertThat(files).hasSize(27); + assertThat(output.resolve("src/main/java/xyz/abcdef/model/Child.java")) + .content().contains("public class Child extends Person {"); + assertThat(output.resolve("src/main/java/xyz/abcdef/model/Adult.java")) + .content().contains("public class Adult extends Person {"); + assertThat(output.resolve("src/main/java/xyz/abcdef/model/AnotherChild.java")) + .content().contains("public class AnotherChild {"); } - @Test - public void testDiscriminatorWithMappingIssue14731() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) - .getOpenAPI(); + @Test public void testDiscriminatorWithMappingIssue14731() { + final Path output = newTempFolder(); + final OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); - JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.setOutputDir(output.getAbsolutePath()); + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setOutputDir(output.toString()); codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); codegen.setUseOneOfInterfaces(true); - - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); - - DefaultGenerator generator = new DefaultGenerator(); - generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); - generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); - codegen.setUseOneOfInterfaces(true); codegen.setLegacyDiscriminatorBehavior(false); codegen.setUseJakartaEe(true); codegen.setModelNameSuffix("DTO"); - generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); - generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); - generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); - generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); - - generator.opts(input).generate(); - - assertFileNotContains( - Paths.get( - outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingADTO.java"), - "@JsonTypeName"); - assertFileNotContains( - Paths.get( - outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingBDTO.java"), - "@JsonTypeName"); - } - - @Test - public void testDiscriminatorWithoutMappingIssue14731() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) - .getOpenAPI(); - - JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.setOutputDir(output.getAbsolutePath()); - codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); - codegen.setUseOneOfInterfaces(true); - - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); + final ClientOptInput input = new ClientOptInput().openAPI(openAPI).config(codegen); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); + generator.opts(input).generate(); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithMappingADTO.java")) + .content().doesNotContain("@JsonTypeName"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithMappingBDTO.java")) + .content().doesNotContain("@JsonTypeName"); + } + + @Test public void testDiscriminatorWithoutMappingIssue14731() { + final Path output = newTempFolder(); + final OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setOutputDir(output.toString()); + codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); + codegen.setUseOneOfInterfaces(true); codegen.setUseOneOfInterfaces(true); codegen.setLegacyDiscriminatorBehavior(false); codegen.setUseJakartaEe(true); codegen.setModelNameSuffix("DTO"); codegen.setLibrary(JavaClientCodegen.RESTTEMPLATE); + final ClientOptInput input = new ClientOptInput().openAPI(openAPI).config(codegen); + DefaultGenerator generator = new DefaultGenerator(); + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); - generator.opts(input).generate(); - assertFileContains( - Paths.get( - outputPath - + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingADTO.java"), - "@JsonTypeName"); - assertFileContains( - Paths.get( - outputPath - + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingBDTO.java"), - "@JsonTypeName"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithoutMappingADTO.java")) + .content().contains("@JsonTypeName"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/ChildWithoutMappingBDTO.java")) + .content().contains("@JsonTypeName"); } - @Test - public void testForJavaNativeJsonSubtype() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) - .getOpenAPI(); - - JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.setOutputDir(output.getAbsolutePath()); - - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); - - DefaultGenerator generator = new DefaultGenerator(); + @Test public void testForJavaNativeJsonSubtype() { + final Path output = newTempFolder(); + final OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); + final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setLibrary(JavaClientCodegen.NATIVE); + codegen.setOutputDir(output.toString()); - generator.opts(input).generate(); + new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"Cat\", Cat.class)"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"cat\", Cat.class);"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"dog\", Dog.class);"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"lizard\", Lizard.class);"); - - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"cat\", Cat.class)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"dog\", Dog.class)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"lizard\", Lizard.class)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"Pet\", Pet.class)"); - - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() + .contains("mappings.put(\"Cat\", Cat.class)") + .doesNotContain( + "@JsonSubTypes", + "mappings.put(\"cat\", Cat.class);", + "mappings.put(\"dog\", Dog.class);", + "mappings.put(\"lizard\", Lizard.class);" + ); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() + .contains( + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")", + "mappings.put(\"cat\", Cat.class)", + "mappings.put(\"dog\", Dog.class)", + "mappings.put(\"lizard\", Lizard.class)", + "mappings.put(\"Pet\", Pet.class)" + ).doesNotContain( + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")" + ); } - @Test - public void shouldProperlyExplodeRestTemplateQueryParameters_issue907() { + @Test public void shouldProperlyExplodeRestTemplateQueryParameters_issue907() { final Map files = generateFromContract( "src/test/resources/3_0/java/explode-query-parameter.yaml", @@ -2406,95 +1846,64 @@ public class JavaClientCodegenTest { final Map properties, final Consumer consumer ) { - final File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(library) - .setAdditionalProperties(properties) - .setInputSpec(pathToSpecification) - .setOutputDir(output.getAbsolutePath()); + .setGeneratorName("java") + .setLibrary(library) + .setAdditionalProperties(properties) + .setInputSpec(pathToSpecification) + .setOutputDir(output.toString()); consumer.accept(configurator); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - final DefaultGenerator generator = new DefaultGenerator(); - return generator.opts(clientOptInput).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + return new DefaultGenerator().opts(configurator.toClientOptInput()).generate() + .stream().collect(Collectors.toMap(File::getName, Function.identity())); } - @Test - public void testForJavaApacheHttpClientJsonSubtype() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) - .getOpenAPI(); + @Test public void testForJavaApacheHttpClientJsonSubtype() { + final Path output = newTempFolder(); + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.setOutputDir(output.getAbsolutePath()); - - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); - - DefaultGenerator generator = new DefaultGenerator(); codegen.setLibrary(JavaClientCodegen.APACHE); + codegen.setOutputDir(output.toString()); - generator.opts(input).generate(); + new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() + .contains( "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" - + " \"petType\", visible = true)"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); + + " \"petType\", visible = true)" + ).doesNotContain( + "mappings.put", + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")" + ); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() + .contains( "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" - + " \"petType\", visible = true)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); + + " \"petType\", visible = true)", + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")" + ).doesNotContain( + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")", + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")", + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")" + ); } - @Test - public void testIsOverriddenProperty() { + @Test public void testIsOverriddenProperty() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf_composition_discriminator.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); - - Schema test1 = openAPI.getComponents().getSchemas().get("Cat"); codegen.setOpenAPI(openAPI); - CodegenModel cm1 = codegen.fromModel("Cat", test1); + CodegenModel cm1 = codegen.fromModel("Cat", openAPI.getComponents().getSchemas().get("Cat")); + CodegenProperty cp0 = cm1.getAllVars().get(0); Assertions.assertEquals(cp0.getName(), "petType"); Assertions.assertEquals(cp0.isOverridden, true); @@ -2504,171 +1913,99 @@ public class JavaClientCodegenTest { Assertions.assertEquals(cp1.isOverridden, false); } - @Test - public void testForJavaApacheHttpClientOverrideSetter() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation( - "src/test/resources/3_0/allOf_composition_discriminator.yaml", - null, - new ParseOptions()) - .getOpenAPI(); + @Test public void testForJavaApacheHttpClientOverrideSetter() { + final Path output = newTempFolder(); + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, null) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.setOutputDir(output.getAbsolutePath()); - - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); - - DefaultGenerator generator = new DefaultGenerator(); + codegen.setOutputDir(output.toString()); codegen.setLibrary(JavaClientCodegen.APACHE); - generator.opts(input).generate(); + new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - " @Override\n" + " public Cat petType(String petType) {"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - " }\n" + "\n" + " public Pet petType(String petType) {\n"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() + .contains(" @Override\n" + " public Cat petType(String petType) {"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() + .contains(" }\n" + "\n" + " public Pet petType(String petType) {\n"); } - @Test - public void testForJavaNativeClientOverrideSetter() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation( - "src/test/resources/3_0/allOf_composition_discriminator.yaml", - null, - new ParseOptions()) - .getOpenAPI(); - - JavaClientCodegen codegen = new JavaClientCodegen(); - codegen.setOutputDir(output.getAbsolutePath()); - - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); - - DefaultGenerator generator = new DefaultGenerator(); + @Test public void testForJavaNativeClientOverrideSetter() { + final Path output = newTempFolder(); + final OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/allOf_composition_discriminator.yaml", null, null) + .getOpenAPI(); + final JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setOutputDir(output.toString()); codegen.setLibrary(JavaClientCodegen.NATIVE); - generator.opts(input).generate(); + new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - " @Override\n" + " public Cat petType(String petType) {"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - " }\n" + "\n" + " public Pet petType(String petType) {\n"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Cat.java")).content() + .contains(" @Override\n" + " public Cat petType(String petType) {"); + assertThat(output.resolve("src/main/java/org/openapitools/client/model/Pet.java")).content() + .contains(" }\n" + "\n" + " public Pet petType(String petType) {\n"); } - @Test - public void testDeprecatedProperty() throws Exception { - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testDeprecatedProperty() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.OKHTTP_GSON) .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - // deprecated builder method TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + " public BigDog declawed(Boolean declawed) {"); - - // deprecated getter - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" - + " @javax.annotation.Nullable\n" - + "\n" - + " public Boolean getDeclawed() {"); - // deprecated setter - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + " public void setDeclawed(Boolean declawed) {"); - - output.deleteOnExit(); + output.resolve("src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n public BigDog declawed(Boolean declawed) {", // deprecated builder method + "@Deprecated\n @javax.annotation.Nullable\n\n public Boolean getDeclawed() {", // deprecated getter + "@Deprecated\n" + " public void setDeclawed(Boolean declawed) {" // deprecated setter + ); } - @Test - public void testDeprecatedPropertyJersey3() throws Exception { - File output = Files.createTempDirectory("test").toFile(); - + @Test public void testDeprecatedPropertyJersey3() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.JERSEY3) .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - // deprecated builder method TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + " public BigDog declawed(Boolean declawed) {"); - - // deprecated getter - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" - + " @jakarta.annotation.Nullable\n" - + " @JsonProperty(JSON_PROPERTY_DECLAWED)\n" - + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n" - + "\n" - + " public Boolean getDeclawed() {"); - // deprecated setter - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" - + " @JsonProperty(JSON_PROPERTY_DECLAWED)\n" - + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n" - + " public void setDeclawed(Boolean declawed) {"); - - output.deleteOnExit(); + output.resolve("src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n public BigDog declawed(Boolean declawed) {", // deprecated builder method + "@Deprecated\n @jakarta.annotation.Nullable\n @JsonProperty(JSON_PROPERTY_DECLAWED)\n" + + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n\n" + + " public Boolean getDeclawed() {", // deprecated getter + "@Deprecated\n @JsonProperty(JSON_PROPERTY_DECLAWED)\n" + + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n" + + " public void setDeclawed(Boolean declawed) {" // deprecated setter + ); } - @DataProvider(name = "shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684") - public static Object[][] shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684_dataProvider() { + @DataProvider + public static Object[][] librariesToRegressionTestForIssue15684() { return new Object[][]{{"okhttp-gson"}, {"jersey2"}, {"jersey3"}, {"native"}}; } - @Test(dataProvider = "shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684") - public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684(String library) throws Exception { - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); + @Test(dataProvider = "librariesToRegressionTestForIssue15684") + public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684(String library) { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(library) + .addAdditionalProperty(AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") + .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(library) - .addAdditionalProperty( - AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") - .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - Map files = generator.opts(clientOptInput).generate().stream() + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("AbstractOpenApiSchema.java")) @@ -2681,408 +2018,249 @@ public class JavaClientCodegenTest { .containsWithName("annotation2"); } - @Test - public void testRestTemplateWithGeneratedClientAsBeanDisabled() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, false); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestTemplateWithGeneratedClientAsBeanDisabled() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, false) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path apiClient = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"); - TestUtils.assertFileNotContains(apiClient, "@Component"); - - Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/PetApi.java"); - TestUtils.assertFileNotContains(petApi, "@Component"); + TestUtils.assertFileNotContains(output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), "@Component"); + TestUtils.assertFileNotContains(output.resolve("src/main/java/xyz/abcdef/api/PetApi.java"), "@Component"); } - @Test - public void testRestTemplateWithGeneratedClientAsBeanEnabled() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestTemplateWithGeneratedClientAsBeanEnabled() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/petstore.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path apiClient = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"); - TestUtils.assertFileContains(apiClient, "@Component"); - - Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/PetApi.java"); - TestUtils.assertFileContains(petApi, "@Component"); + TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), "@Component"); + TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/api/PetApi.java"), "@Component"); } - @Test - public void testRestTemplateWithUseBeanValidationEnabled() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_BEANVALIDATION, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestTemplateWithUseBeanValidationEnabled() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, true) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path pomFile = Paths.get(output + "/pom.xml"); - TestUtils.assertFileContains(pomFile, "jakarta.validation-api"); - - Path petModel = Paths.get(output + "/src/main/java/org/openapitools/client/model/Pet.java"); - TestUtils.assertFileContains(petModel, "@Valid"); + TestUtils.assertFileContains(output.resolve("pom.xml"), "jakarta.validation-api"); + TestUtils.assertFileContains(output.resolve("src/main/java/org/openapitools/client/model/Pet.java"), "@Valid"); } - @Test - public void testRestTemplateWithUseBeanValidationDisabled() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_BEANVALIDATION, false); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestTemplateWithUseBeanValidationDisabled() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_BEANVALIDATION, false) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path pomFile = Paths.get(output + "/pom.xml"); - TestUtils.assertFileNotContains(pomFile, "jakarta.validation-api"); - - Path petModel = Paths.get(output + "/src/main/java/org/openapitools/client/model/Pet.java"); - TestUtils.assertFileNotContains(petModel, "@Valid"); + TestUtils.assertFileNotContains(output.resolve("pom.xml"), "jakarta.validation-api"); + TestUtils.assertFileNotContains(output.resolve("src/main/java/org/openapitools/client/model/Pet.java"), "@Valid"); } - @Test - public void testRestTemplateWithPerformBeanValidationEnabled() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.PERFORM_BEANVALIDATION, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestTemplateWithPerformBeanValidationEnabled() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.PERFORM_BEANVALIDATION, true) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path pomFile = Paths.get(output + "/pom.xml"); - TestUtils.assertFileContains(pomFile, "hibernate-validator"); - - Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/BeanValidationException.java"); - TestUtils.assertFileExists(petApi); + TestUtils.assertFileContains(output.resolve("pom.xml"), "hibernate-validator"); + TestUtils.assertFileExists(output.resolve("src/main/java/xyz/abcdef/BeanValidationException.java")); } - @Test - public void testRestTemplateWithPerformBeanValidationDisabled() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.PERFORM_BEANVALIDATION, false); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestTemplateWithPerformBeanValidationDisabled() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.PERFORM_BEANVALIDATION, false) .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) .setInputSpec("src/test/resources/3_0/petstore.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path pomFile = Paths.get(output + "/pom.xml"); - TestUtils.assertFileNotContains(pomFile, "hibernate-validator"); - - Path petApi = Paths.get(output + "/src/main/java/org/openapitools/client/invoker/BeanValidationException.java"); - TestUtils.assertFileNotExists(petApi); + TestUtils.assertFileNotContains(output.resolve("pom.xml"), "hibernate-validator"); + TestUtils.assertFileNotExists(output.resolve("src/main/java/org/openapitools/client/invoker/BeanValidationException.java")); } - - @Test - public void testLogicToAvoidStackOverflow() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testLogicToAvoidStackOverflow() { final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/issue_12929.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.GENERATE_CLIENT_AS_BEAN, true) + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setInputSpec("src/test/resources/3_0/issue_12929.yaml") + .setOutputDir(newTempFolder().toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); // shouldn't throw stackoverflow exception } - @Test - public void testWebClientSupportListOfStringReturnType_issue7118() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testWebClientSupportListOfStringReturnType_issue7118() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/bugs/issue_7118.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/bugs/issue_7118.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path userApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/UsersApi.java"); - TestUtils.assertFileContains( - userApi, + assertThat(output.resolve("src/main/java/xyz/abcdef/api/UsersApi.java")).content() + .contains( // set of string "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference>() {};", + + " ParameterizedTypeReference>() {};", "getUserIdSetRequestCreation().toEntity(localVarReturnType)", // list of string "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference>() {};", - "getUserIdListRequestCreation().toEntity(localVarReturnType)"); + + " ParameterizedTypeReference>() {};", + "getUserIdListRequestCreation().toEntity(localVarReturnType)" + ); } - @Test - public void testEnumCaseInsensitive_issue8084() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - + @Test public void testEnumCaseInsensitive_issue8084() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/issue8084.yaml"); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOpenAPI(openAPI); - codegen.setOutputDir(output.getAbsolutePath()); + codegen.setOutputDir(newTempFolder().toString()); codegen.additionalProperties().put(USE_ENUM_CASE_INSENSITIVE, "true"); - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); + Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); - DefaultGenerator generator = new DefaultGenerator(); - - Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); - - JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(files.get("EnumTest.java")); - javaFileAssert + JavaFileAssert.assertThat(files.get("EnumTest.java")) .assertMethod("fromValue") .bodyContainsLines("if (b.value.equalsIgnoreCase(value)) {"); } - @Test - public void testEnumCaseSensitive_issue8084() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - + @Test public void testEnumCaseSensitive_issue8084() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/2_0/issue8084.yaml"); final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOpenAPI(openAPI); - codegen.setOutputDir(output.getAbsolutePath()); + codegen.setOutputDir(newTempFolder().toString()); codegen.additionalProperties().put(USE_ENUM_CASE_INSENSITIVE, "false"); - ClientOptInput input = new ClientOptInput(); - input.openAPI(openAPI); - input.config(codegen); + Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); - DefaultGenerator generator = new DefaultGenerator(); - - Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); - - JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(files.get("EnumTest.java")); - javaFileAssert - .assertMethod("fromValue") - .bodyContainsLines("if (b.value.equals(value)) {"); + JavaFileAssert.assertThat(files.get("EnumTest.java")) + .assertMethod("fromValue") + .bodyContainsLines("if (b.value.equals(value)) {"); } - @Test - public void testWebClientResponseTypeWithUseAbstractionForFiles_issue16589() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testWebClientResponseTypeWithUseAbstractionForFiles_issue16589() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/ResourceApi.java"); - - TestUtils.assertFileContains(defaultApi, + TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/api/ResourceApi.java"), "Mono resourceInResponse()", "Mono> resourceInResponseWithHttpInfo()", "ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference()" ); } - @Test - public void testHandleConstantParams() throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); + @Test public void testHandleConstantParams() { + final Path output = newTempFolder(); final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/java/autoset_constant.yaml"); - final DefaultGenerator defaultGenerator = new DefaultGenerator(); - final ClientOptInput clientOptInput = new ClientOptInput(); - clientOptInput.openAPI(openAPI); - JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); - javaClientCodegen.setOutputDir(output.getAbsolutePath()); - javaClientCodegen.additionalProperties().put(CodegenConstants.AUTOSET_CONSTANTS, "true"); - javaClientCodegen.setAutosetConstants(true); - clientOptInput.config(javaClientCodegen); - defaultGenerator.opts(clientOptInput); + JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setOutputDir(output.toString()); + codegen.additionalProperties().put(CodegenConstants.AUTOSET_CONSTANTS, "true"); + codegen.setAutosetConstants(true); - Map files = defaultGenerator.generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); File apiFile = files.get("HelloExampleApi.java"); - Assertions.assertNotNull(apiFile); JavaFileAssert.assertThat(apiFile) - .assertMethod("helloCall", "String", "ApiCallback") - .bodyContainsLines( - "localVarHeaderParams.put(\"X-CUSTOM_CONSTANT_HEADER\", \"CONSTANT_VALUE\")"); + .assertMethod("helloCall", "String", "ApiCallback") + .bodyContainsLines("localVarHeaderParams.put(\"X-CUSTOM_CONSTANT_HEADER\", \"CONSTANT_VALUE\")"); } @Test - public void testAllOfWithSinglePrimitiveTypeRef() throws IOException { - File output = Files.createTempDirectory("test_allOf_primitive_type").toFile().getCanonicalFile(); - output.deleteOnExit(); + public void testAllOfWithSinglePrimitiveTypeRef() { + final Path output = newTempFolder(); final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allof_primitive.yaml"); - final DefaultGenerator defaultGenerator = new DefaultGenerator(); - final ClientOptInput clientOptInput = new ClientOptInput(); - clientOptInput.openAPI(openAPI); - JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); - javaClientCodegen.setOutputDir(output.getAbsolutePath()); - javaClientCodegen.setAutosetConstants(true); - clientOptInput.config(javaClientCodegen); - defaultGenerator.opts(clientOptInput); + JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setOutputDir(output.toString()); + codegen.setAutosetConstants(true); - Map files = defaultGenerator.generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); - File apiFile = files.get("AllOfDatetime.java"); - assertEquals(apiFile, null); + assertNull(files.get("AllOfDatetime.java")); } - @Test - public void testOpenapiGeneratorIgnoreListOption() throws IOException { - File output = Files.createTempDirectory("openapi_generator_ignore_list_test_folder").toFile().getCanonicalFile(); - output.deleteOnExit(); + @Test public void testOpenapiGeneratorIgnoreListOption() { + final Path output = newTempFolder(); final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allof_primitive.yaml"); - final DefaultGenerator defaultGenerator = new DefaultGenerator(); - final ClientOptInput clientOptInput = new ClientOptInput(); - clientOptInput.openAPI(openAPI); - JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); - javaClientCodegen.setOutputDir(output.getAbsolutePath()); - javaClientCodegen.setAutosetConstants(true); - javaClientCodegen.openapiGeneratorIgnoreList().add("README.md"); - javaClientCodegen.openapiGeneratorIgnoreList().add("pom.xml"); - clientOptInput.config(javaClientCodegen); - defaultGenerator.opts(clientOptInput); - - Map files = defaultGenerator.generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + JavaClientCodegen codegen = new JavaClientCodegen(); + codegen.setOutputDir(output.toString()); + codegen.setAutosetConstants(true); + codegen.openapiGeneratorIgnoreList().add("README.md"); + codegen.openapiGeneratorIgnoreList().add("pom.xml"); + + Map files = new DefaultGenerator().opts(new ClientOptInput().openAPI(openAPI).config(codegen)) + .generate().stream().collect(Collectors.toMap(File::getName, Function.identity())); // make sure README.md and pom.xml are not generated - assertEquals(files.get("README.md"), null); - assertEquals(files.get("pom.xml"), null); + assertNull(files.get("README.md")); + assertNull(files.get("pom.xml")); } @Test - public void testRestTemplateHandleURIEnum() throws IOException { + public void testRestTemplateHandleURIEnum() { String[] expectedInnerEnumLines = new String[] { "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))" @@ -3097,7 +2275,7 @@ public class JavaClientCodegenTest { } @Test - public void testOkHttpGsonHandleURIEnum() throws IOException { + public void testOkHttpGsonHandleURIEnum() { String[] expectedInnerEnumLines = new String[] { "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", @@ -3118,7 +2296,7 @@ public class JavaClientCodegenTest { } @Test - public void testMicroprofileHandleURIEnum() throws IOException { + public void testMicroprofileHandleURIEnum() { String[] expectedInnerEnumLines = new String[] { "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", @@ -3133,23 +2311,16 @@ public class JavaClientCodegenTest { testHandleURIEnum(JavaClientCodegen.MICROPROFILE, expectedInnerEnumLines, expectedEnumLines); } - private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, String[] expectedEnumLines) throws IOException { - File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); - output.deleteOnExit(); - + private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, String[] expectedEnumLines) { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(library) .setInputSpec("src/test/resources/3_0/enum-and-inner-enum-uri.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - final DefaultGenerator defaultGenerator = new DefaultGenerator(); - - defaultGenerator.opts(clientOptInput); - - Map files = defaultGenerator.generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .setOutputDir(output.toString().replace("\\", "/")); + + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate() + .stream().collect(Collectors.toMap(File::getName, Function.identity())); // enum File modelFile = files.get("Metadata.java"); @@ -3162,36 +2333,22 @@ public class JavaClientCodegenTest { JavaFileAssert.assertThat(apiFile).fileContains(expectedInnerEnumLines); } - @Test - public void testQueryParamsExploded_whenQueryParamIsNull() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testQueryParamsExploded_whenQueryParamIsNull() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTTEMPLATE) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/issue_17555.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setOutputDir(output.toString().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - - Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/DepartmentApi.java"); - TestUtils.assertFileContains(petApi, "if (filter != null) {"); + TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/api/DepartmentApi.java"), "if (filter != null) {"); } - @Test - public void generateAllArgsConstructor() { + @Test public void generateAllArgsConstructor() { Map files = generateFromContract("src/test/resources/3_0/java/all_args_constructor.yaml", JavaClientCodegen.RESTTEMPLATE, Map.of(AbstractJavaCodegen.GENERATE_CONSTRUCTOR_WITH_ALL_ARGS, Boolean.TRUE), codegenConfigurator -> codegenConfigurator.addOpenapiNormalizer("REFACTOR_ALLOF_WITH_PROPERTIES_ONLY", "false")); @@ -3222,8 +2379,7 @@ public class JavaClientCodegenTest { .hasParameter("_list").toConstructor(); } - @Test - public void generateAllArgsConstructor_REFACTOR_ALLOF_WITH_PROPERTIES_ONLY() { + @Test public void generateAllArgsConstructor_REFACTOR_ALLOF_WITH_PROPERTIES_ONLY() { // try the generation with some additional OpenAPINormalizers Map files = generateFromContract("src/test/resources/3_0/java/all_args_constructor.yaml", JavaClientCodegen.RESTTEMPLATE, @@ -3251,225 +2407,216 @@ public class JavaClientCodegenTest { .assertConstructor("Integer", "String", "LocalDate", "String", "String"); } - @Test - public void testRestClientFormMultipart() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - + @Test public void testRestClientFormMultipart() { + final Path output = newTempFolder(); final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setLibrary(JavaClientCodegen.RESTCLIENT) - .setAdditionalProperties(properties) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); TestUtils.assertFileContains( - defaultApi, - // multiple files - "multipartArray(List files)", - "formParams.addAll(\"files\"," - + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java"), + // multiple files + "multipartArray(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - // mixed - "multipartMixed(MultipartMixedStatus status, File _file, MultipartMixedRequestMarker marker, List statusArray)", - "formParams.add(\"file\", new FileSystemResource(_file));", + // mixed + "multipartMixed(MultipartMixedStatus status, File _file, MultipartMixedRequestMarker marker, List statusArray)", + "formParams.add(\"file\", new FileSystemResource(_file));", - // single file - "multipartSingle(File _file)", - "formParams.add(\"file\", new FileSystemResource(_file));"); - } - - @Test - public void testRestClientWithUseAbstractionForFiles() throws IOException { - - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); - - validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, - // multiple files - "multipartArray(java.util.Collection files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - - // mixed - "multipartMixed(MultipartMixedStatus status, org.springframework.core.io.AbstractResource _file, MultipartMixedRequestMarker marker, List statusArray)", - "formParams.add(\"file\", _file);", - - // single file - "multipartSingle(org.springframework.core.io.AbstractResource _file)", - "formParams.add(\"file\", _file);"); - } - - @Test - public void testRestClientWithFreeFormInQueryParameters() throws IOException { - final Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - - final File output = Files.createTempDirectory("test") - .toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/issue8352.yaml") - .setOutputDir(output.getAbsolutePath() - .replace("\\", "/")); - - final DefaultGenerator generator = new DefaultGenerator(); - final List files = generator.opts(configurator.toClientOptInput()) - .generate(); - files.forEach(File::deleteOnExit); - - validateJavaSourceFiles(files); - - final Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"); - TestUtils.assertFileContains(defaultApi, "value instanceof Map"); - } - - @Test - public void testRestClientJsonCreatorWithNullable_issue12790() throws Exception { - Map properties = new HashMap<>(); - properties.put(AbstractJavaCodegen.OPENAPI_NULLABLE, "true"); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setAdditionalProperties(properties) - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setInputSpec("src/test/resources/bugs/issue_12790.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - Map files = generator.opts(clientOptInput).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); - - JavaFileAssert.assertThat(files.get("TestObject.java")) - .printFileContent() - .assertConstructor("String", "String") - .bodyContainsLines( - "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() :" - + " JsonNullable.of(nullableProperty);", - "this.notNullableProperty = notNullableProperty;"); - } - - @Test - public void testRestClientSupportListOfStringReturnType_issue7118() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/bugs/issue_7118.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); - - validateJavaSourceFiles(files); - - Path userApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/UsersApi.java"); - TestUtils.assertFileContains( - userApi, - // set of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference<>() {};", - "getUserIdSetRequestCreation().toEntity(localVarReturnType)", - // list of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference<>() {};", - "getUserIdListRequestCreation().toEntity(localVarReturnType)"); - } - - @Test - public void testRestClientResponseTypeWithUseAbstractionForFiles_issue16589() throws IOException { - Map properties = new HashMap<>(); - properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); - properties.put(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true); - - File output = Files.createTempDirectory("test").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.RESTCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - files.forEach(File::deleteOnExit); - - validateJavaSourceFiles(files); - - Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/ResourceApi.java"); - - TestUtils.assertFileContains(defaultApi, - "org.springframework.core.io.Resource resourceInResponse()", - "ResponseEntity resourceInResponseWithHttpInfo()", - "ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>()" + // single file + "multipartSingle(File _file)", + "formParams.add(\"file\", new FileSystemResource(_file));" ); } - @Test - void testBuilderJavaClient() throws IOException { - Map files = generateFromContract("src/test/resources/3_0/java/builder.yaml", JavaClientCodegen.RESTTEMPLATE, - Map.of(AbstractJavaCodegen.GENERATE_BUILDERS, Boolean.TRUE)); + @Test public void testRestClientWithUseAbstractionForFiles() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + TestUtils.assertFileContains( + output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java"), + // multiple files + "multipartArray(java.util.Collection files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + + // mixed + "multipartMixed(MultipartMixedStatus status, org.springframework.core.io.AbstractResource _file, MultipartMixedRequestMarker marker, List statusArray)", + "formParams.add(\"file\", _file);", + + // single file + "multipartSingle(org.springframework.core.io.AbstractResource _file)", + "formParams.add(\"file\", _file);" + ); + } + + @Test public void testRestClientWithFreeFormInQueryParameters() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator().setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setAdditionalProperties(Map.of(CodegenConstants.API_PACKAGE, "xyz.abcdef.api")) + .setInputSpec("src/test/resources/3_0/issue8352.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + final List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + TestUtils.assertFileContains(output.resolve("src/main/java/xyz/abcdef/ApiClient.java"), "value instanceof Map"); + } + + @Test public void testRestClientJsonCreatorWithNullable_issue12790() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .addAdditionalProperty(AbstractJavaCodegen.OPENAPI_NULLABLE, "true") + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/bugs/issue_12790.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + Map files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + JavaFileAssert.assertThat(files.get("TestObject.java")) + .printFileContent() + .assertConstructor("String", "String") + .bodyContainsLines( + "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() :" + + " JsonNullable.of(nullableProperty);", + "this.notNullableProperty = notNullableProperty;" + ); + } + + @Test public void testRestClientSupportListOfStringReturnType_issue7118() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/bugs/issue_7118.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + TestUtils.assertFileContains( + output.resolve("src/main/java/xyz/abcdef/api/UsersApi.java"), + // set of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference<>() {};", + "getUserIdSetRequestCreation().toEntity(localVarReturnType)", + // list of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference<>() {};", + "getUserIdListRequestCreation().toEntity(localVarReturnType)" + ); + } + + @Test public void testRestClientResponseTypeWithUseAbstractionForFiles_issue16589() { + final Path output = newTempFolder(); + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .addAdditionalProperty(JavaClientCodegen.USE_ABSTRACTION_FOR_FILES, true) + .setLibrary(JavaClientCodegen.RESTCLIENT) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + TestUtils.assertFileContains( + output.resolve("src/main/java/xyz/abcdef/api/ResourceApi.java"), + "org.springframework.core.io.Resource resourceInResponse()", + "ResponseEntity resourceInResponseWithHttpInfo()", + "ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>()" + ); + } + + @Test void testBuilderJavaClient() { + Map files = generateFromContract( + "src/test/resources/3_0/java/builder.yaml", + JavaClientCodegen.RESTTEMPLATE, + Map.of(AbstractJavaCodegen.GENERATE_BUILDERS, Boolean.TRUE) + ); + JavaFileAssert.assertThat(files.get("Pet.java")) - .fileContains("protected String petReadonlyProperty", - "toBuilder()", - "builder()", - "public static class Builder {"); + .fileContains( + "protected String petReadonlyProperty", "toBuilder()", "builder()", "public static class Builder {" + ); JavaFileAssert.assertThat(files.get("Snake.java")) - .fileContains("toBuilder()", - "builder()", - "public static class Builder extends Reptile.Builder {", - ".petType(getPetType())", - ".name(getName())", - "hasLegs(getHasLegs())"); + .fileContains( + "toBuilder()", + "builder()", + "public static class Builder extends Reptile.Builder {", + ".petType(getPetType())", + ".name(getName())", + "hasLegs(getHasLegs())" + ); + } + + @DataProvider Iterator serializationLibraries() { + return new JavaClientCodegen().supportedLibraries().keySet().iterator(); + } + + @Test(dataProvider = "serializationLibraries") void setsDefaultSerializationLibrary(String library) { + var codegen = new JavaClientCodegen(); + codegen.setLibrary(library); + codegen.processOpts(); + + assertThat(codegen.additionalProperties()) + .containsAnyOf( + entry(SERIALIZATION_LIBRARY_GSON, "true"), + entry(SERIALIZATION_LIBRARY_JACKSON, "true"), + entry(SERIALIZATION_LIBRARY_JSONB, "true") + ); + } + + /** + * Regression test for #18515: + * When GSON is selected as serializer, there should not be any jackson references + * (except jackson-databind-nullable that is, which is only added when openApiNullable=true) + */ + @Test(dataProvider = "librariesSupportingGson") void gsonCodeDoesNotContainJacksonReferences(Library library) { + final CodegenConfigurator configurator = new CodegenConfigurator() + .addAdditionalProperty(SERIALIZATION_LIBRARY, Serializer.GSON) + .addAdditionalProperty(OPENAPI_NULLABLE, "false") + .setGeneratorName("java") + .setLibrary(library.getValue()) + .setInputSpec("src/test/resources/3_0/java/autoset_constant.yaml") + .setOutputDir(newTempFolder().toString()); + var generator = new DefaultGenerator(); + generator.setGenerateMetadata(false); + + List files = generator.opts(configurator.toClientOptInput()).generate(); + + assertThat(files).allSatisfy( + file -> assertThat(file).content().doesNotContainIgnoringCase("jackson") + ); + } + + static private Path newTempFolder() { + try { + var tempDir = Files.createTempDirectory("test"); + tempDir.toFile().deleteOnExit(); + return tempDir; + } catch (IOException e) { + throw new RuntimeException(e); + } } } diff --git a/samples/client/echo_api/java/feign-gson/build.gradle b/samples/client/echo_api/java/feign-gson/build.gradle index 1ba4f496250..9c613d0b26c 100644 --- a/samples/client/echo_api/java/feign-gson/build.gradle +++ b/samples/client/echo_api/java/feign-gson/build.gradle @@ -102,8 +102,6 @@ test { ext { swagger_annotations_version = "1.6.11" - jackson_version = "2.17.1" - jackson_databind_version = "2.17.1" jackson_databind_nullable_version = "0.2.6" jakarta_annotation_version = "1.3.5" feign_version = "10.12" @@ -116,15 +114,10 @@ dependencies { implementation "io.swagger:swagger-annotations:$swagger_annotations_version" implementation "com.google.code.findbugs:jsr305:3.0.2" implementation "io.github.openfeign:feign-core:$feign_version" - implementation "io.github.openfeign:feign-jackson:$feign_version" implementation "io.github.openfeign:feign-slf4j:$feign_version" implementation "io.github.openfeign:feign-okhttp:$feign_version" implementation "io.github.openfeign.form:feign-form:$feign_form_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 "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" - implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" implementation "com.brsanthu:migbase64:2.2" implementation "com.github.scribejava:scribejava-core:$scribejava_version" implementation "com.brsanthu:migbase64:2.2" diff --git a/samples/client/echo_api/java/feign-gson/build.sbt b/samples/client/echo_api/java/feign-gson/build.sbt index 4dad7caf361..a44105b5904 100644 --- a/samples/client/echo_api/java/feign-gson/build.sbt +++ b/samples/client/echo_api/java/feign-gson/build.sbt @@ -12,15 +12,9 @@ lazy val root = (project in file(".")). "io.swagger" % "swagger-annotations" % "1.6.11" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "io.github.openfeign" % "feign-core" % "10.12" % "compile", - "io.github.openfeign" % "feign-jackson" % "10.12" % "compile", "io.github.openfeign" % "feign-slf4j" % "10.12" % "compile", "io.github.openfeign.form" % "feign-form" % "3.8.0" % "compile", "io.github.openfeign" % "feign-okhttp" % "10.12" % "compile", - "com.fasterxml.jackson.core" % "jackson-core" % "2.17.1" % "compile", - "com.fasterxml.jackson.core" % "jackson-annotations" % "2.17.1" % "compile", - "com.fasterxml.jackson.core" % "jackson-databind" % "2.17.1" % "compile", - "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.17.1" % "compile", - "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.15.2" % "compile", "com.github.scribejava" % "scribejava-core" % "8.0.0" % "compile", "com.brsanthu" % "migbase64" % "2.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/echo_api/java/feign-gson/pom.xml b/samples/client/echo_api/java/feign-gson/pom.xml index cbad269929c..f0ea88c5bd6 100644 --- a/samples/client/echo_api/java/feign-gson/pom.xml +++ b/samples/client/echo_api/java/feign-gson/pom.xml @@ -304,7 +304,6 @@ 3.8.0 2.10.1 0.2.6 - 2.17.1 1.3.5 5.10.0 1.0.0 diff --git a/samples/client/echo_api/java/okhttp-gson-user-defined-templates/src/main/java/org/openapitools/client/JSON.java b/samples/client/echo_api/java/okhttp-gson-user-defined-templates/src/main/java/org/openapitools/client/JSON.java index ad2d26cbfbb..f993e935c7a 100644 --- a/samples/client/echo_api/java/okhttp-gson-user-defined-templates/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/echo_api/java/okhttp-gson-user-defined-templates/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -338,7 +331,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -348,7 +341,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -373,7 +366,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -392,7 +385,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java index 1520a2c9357..247f3cf0c99 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -342,7 +335,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -352,7 +345,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -377,7 +370,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -396,7 +389,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/JSON.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/JSON.java index f4e972e414e..c6b151d0ccc 100644 --- a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -333,7 +326,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -343,7 +336,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -368,7 +361,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -387,7 +380,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java index 2aac67fb5b2..999628dc1f7 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -334,7 +327,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -344,7 +337,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -369,7 +362,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -388,7 +381,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/feign/build.gradle b/samples/client/petstore/java/feign/build.gradle index b4e66382bbb..756d3c28211 100644 --- a/samples/client/petstore/java/feign/build.gradle +++ b/samples/client/petstore/java/feign/build.gradle @@ -123,8 +123,8 @@ dependencies { 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 "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" implementation "com.brsanthu:migbase64:2.2" implementation "com.github.scribejava:scribejava-core:$scribejava_version" implementation "com.brsanthu:migbase64:2.2" diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 7afdef65e22..59ae4c527f6 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -319,8 +319,8 @@ 13.2.1 3.8.0 2.17.1 - 0.2.6 2.17.1 + 0.2.6 1.3.5 5.10.0 1.0.0 diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java index f5823fd7522..6fe26034d7e 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -378,7 +371,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -388,7 +381,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -413,7 +406,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -432,7 +425,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/JSON.java index ad2d26cbfbb..f993e935c7a 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -338,7 +331,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -348,7 +341,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -373,7 +366,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -392,7 +385,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/JSON.java index 349f4ff8113..6d80edba2a7 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -413,7 +406,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -423,7 +416,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -448,7 +441,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -467,7 +460,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/JSON.java index ad2d26cbfbb..f993e935c7a 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -338,7 +331,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -348,7 +341,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -373,7 +366,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -392,7 +385,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/JSON.java index 75faa7a82b3..cc08e8c32f4 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -340,7 +333,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -350,7 +343,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -375,7 +368,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -394,7 +387,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/JSON.java index 349f4ff8113..6d80edba2a7 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -413,7 +406,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -423,7 +416,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -448,7 +441,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -467,7 +460,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/JSON.java index ad2d26cbfbb..f993e935c7a 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -338,7 +331,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -348,7 +341,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -373,7 +366,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -392,7 +385,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/JSON.java index ad2d26cbfbb..f993e935c7a 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -338,7 +331,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -348,7 +341,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -373,7 +366,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -392,7 +385,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index dbf329da8a7..5bd5c322fee 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -305,11 +305,6 @@ jackson-databind-nullable ${jackson-databind-nullable-version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - javax.ws.rs jsr311-api @@ -350,7 +345,6 @@ 2.10.1 3.13.0 0.2.6 - 2.16.0 1.3.5 5.10.0 1.10.0 diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java index db57f2dbba8..d13cb5a17e5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -31,16 +31,14 @@ import java.io.StringReader; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; +import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; /* * A JSON utility class @@ -57,11 +55,6 @@ public class JSON { private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -562,7 +555,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -572,7 +565,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -597,7 +590,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -616,7 +609,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/rest-assured-jackson/pom.xml b/samples/client/petstore/java/rest-assured-jackson/pom.xml index 406ffa844b6..8456b100c80 100644 --- a/samples/client/petstore/java/rest-assured-jackson/pom.xml +++ b/samples/client/petstore/java/rest-assured-jackson/pom.xml @@ -227,11 +227,6 @@ rest-assured ${rest-assured.version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - com.fasterxml.jackson.core @@ -241,6 +236,10 @@ com.fasterxml.jackson.core jackson-annotations + + com.fasterxml.jackson.core + jackson-databind + org.openapitools jackson-databind-nullable @@ -281,8 +280,8 @@ 5.3.2 2.10.1 1.9.0 - 2.17.1 2.17.1 + 2.17.1 0.2.6 1.3.5 3.0.2 diff --git a/samples/client/petstore/java/rest-assured/pom.xml b/samples/client/petstore/java/rest-assured/pom.xml index 7f3dc3d7b1b..cabf0fdd6c4 100644 --- a/samples/client/petstore/java/rest-assured/pom.xml +++ b/samples/client/petstore/java/rest-assured/pom.xml @@ -226,11 +226,6 @@ gson-fire ${gson-fire-version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - com.squareup.okio okio @@ -262,7 +257,6 @@ 5.3.2 2.10.1 1.9.0 - 2.17.1 1.3.5 3.0.2 3.6.0 diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/JSON.java index 5f2e9f70d67..edcc9eed5b9 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -35,14 +35,11 @@ import java.text.ParseException; import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; public class JSON { private Gson gson; @@ -53,11 +50,6 @@ public class JSON { private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - @SuppressWarnings("unchecked") public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -380,7 +372,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -390,7 +382,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -415,7 +407,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -434,7 +426,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/retrofit2-play26/build.gradle b/samples/client/petstore/java/retrofit2-play26/build.gradle index 65e19862e45..fac37c81556 100644 --- a/samples/client/petstore/java/retrofit2-play26/build.gradle +++ b/samples/client/petstore/java/retrofit2-play26/build.gradle @@ -99,8 +99,8 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - jackson_databind_version = "2.17.1" jackson_version = "2.17.1" + jackson_databind_version = "2.17.1" javax_ws_rs_api_version = "2.1.1" jackson_databind_nullable_version = "0.2.6" play_version = "2.6.7" @@ -125,10 +125,10 @@ dependencies { implementation "com.squareup.retrofit2:converter-jackson:$retrofit_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 "javax.ws.rs:javax.ws.rs-api:$javax_ws_rs_api_version" implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" - implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" testImplementation "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2-play26/pom.xml b/samples/client/petstore/java/retrofit2-play26/pom.xml index 732655acbd6..f13843c9821 100644 --- a/samples/client/petstore/java/retrofit2-play26/pom.xml +++ b/samples/client/petstore/java/retrofit2-play26/pom.xml @@ -204,11 +204,6 @@ swagger-annotations ${swagger-annotations-version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - com.google.code.findbugs @@ -252,6 +247,11 @@ jackson-annotations ${jackson-version} + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + org.openapitools jackson-databind-nullable @@ -277,6 +277,11 @@ play-ahc-ws_2.12 ${play-version} + + jakarta.validation + jakarta.validation-api + ${beanvalidation-version} + jakarta.annotation jakarta.annotation-api diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle index 446844a46b7..1a891a2ef80 100644 --- a/samples/client/petstore/java/retrofit2/build.gradle +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -99,7 +99,6 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - jackson_databind_version = "2.17.1" jakarta_annotation_version = "1.3.5" swagger_annotations_version = "1.5.22" junit_version = "4.13.2" @@ -116,7 +115,6 @@ dependencies { exclude group:'org.apache.oltu.oauth2' , module: 'org.apache.oltu.oauth2.common' } implementation "io.gsonfire:gson-fire:$json_fire_version" - implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" testImplementation "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index f693aef51c4..27a703dff56 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -204,11 +204,6 @@ swagger-annotations ${swagger-annotations-version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - com.google.code.findbugs @@ -267,7 +262,6 @@ ${java.version} 1.9.0 1.6.3 - 2.17.1 2.5.0 1.3.5 1.0.1 diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/JSON.java index bce9a553a7d..65ad4ef6f55 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -34,14 +34,11 @@ import java.text.ParseException; import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; public class JSON { private Gson gson; @@ -50,11 +47,6 @@ public class JSON { private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() .registerTypeSelector(Animal.class, new TypeSelector() { @@ -293,7 +285,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -303,7 +295,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -329,7 +321,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -348,7 +340,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/retrofit2rx2/build.gradle b/samples/client/petstore/java/retrofit2rx2/build.gradle index 599c09e63b9..4bad500d242 100644 --- a/samples/client/petstore/java/retrofit2rx2/build.gradle +++ b/samples/client/petstore/java/retrofit2rx2/build.gradle @@ -99,7 +99,6 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - jackson_databind_version = "2.17.1" jakarta_annotation_version = "1.3.5" swagger_annotations_version = "1.5.22" junit_version = "4.13.2" @@ -119,7 +118,6 @@ dependencies { exclude group:'org.apache.oltu.oauth2' , module: 'org.apache.oltu.oauth2.common' } implementation "io.gsonfire:gson-fire:$json_fire_version" - implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" testImplementation "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2rx2/pom.xml b/samples/client/petstore/java/retrofit2rx2/pom.xml index 0e22eeffeef..283c5647bd8 100644 --- a/samples/client/petstore/java/retrofit2rx2/pom.xml +++ b/samples/client/petstore/java/retrofit2rx2/pom.xml @@ -204,11 +204,6 @@ swagger-annotations ${swagger-annotations-version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - com.google.code.findbugs @@ -277,7 +272,6 @@ ${java.version} 1.9.0 1.6.3 - 2.17.1 2.5.0 2.1.1 1.3.5 diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/JSON.java index bce9a553a7d..65ad4ef6f55 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -34,14 +34,11 @@ import java.text.ParseException; import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; public class JSON { private Gson gson; @@ -50,11 +47,6 @@ public class JSON { private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() .registerTypeSelector(Animal.class, new TypeSelector() { @@ -293,7 +285,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -303,7 +295,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -329,7 +321,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -348,7 +340,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); } diff --git a/samples/client/petstore/java/retrofit2rx3/build.gradle b/samples/client/petstore/java/retrofit2rx3/build.gradle index 4e167dcf7d4..29bfb6738e9 100644 --- a/samples/client/petstore/java/retrofit2rx3/build.gradle +++ b/samples/client/petstore/java/retrofit2rx3/build.gradle @@ -99,7 +99,6 @@ if(hasProperty('target') && target == 'android') { ext { oltu_version = "1.0.1" retrofit_version = "2.3.0" - jackson_databind_version = "2.17.1" jakarta_annotation_version = "1.3.5" swagger_annotations_version = "1.5.22" junit_version = "4.13.2" @@ -119,7 +118,6 @@ dependencies { exclude group:'org.apache.oltu.oauth2' , module: 'org.apache.oltu.oauth2.common' } implementation "io.gsonfire:gson-fire:$json_fire_version" - implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" testImplementation "junit:junit:$junit_version" } diff --git a/samples/client/petstore/java/retrofit2rx3/pom.xml b/samples/client/petstore/java/retrofit2rx3/pom.xml index 60aed492be9..5546912ccb1 100644 --- a/samples/client/petstore/java/retrofit2rx3/pom.xml +++ b/samples/client/petstore/java/retrofit2rx3/pom.xml @@ -204,11 +204,6 @@ swagger-annotations ${swagger-annotations-version} - - com.fasterxml.jackson.core - jackson-databind - ${jackson-databind-version} - com.google.code.findbugs @@ -277,7 +272,6 @@ ${java.version} 1.9.0 1.6.3 - 2.17.1 2.5.0 3.0.4 1.3.5 diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/JSON.java index bce9a553a7d..65ad4ef6f55 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/JSON.java @@ -13,11 +13,11 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.StdDateFormat; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonParseException; import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import com.google.gson.JsonElement; @@ -34,14 +34,11 @@ import java.text.ParseException; import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.time.ZoneOffset; -import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Locale; import java.util.Map; import java.util.HashMap; -import java.util.TimeZone; public class JSON { private Gson gson; @@ -50,11 +47,6 @@ public class JSON { private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private static final StdDateFormat sdf = new StdDateFormat() - .withTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault())) - .withColonInTimeZone(true); - private static final DateTimeFormatter dtf = DateTimeFormatter.ISO_OFFSET_DATE_TIME; - public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() .registerTypeSelector(Animal.class, new TypeSelector() { @@ -293,7 +285,7 @@ public class JSON { if (dateFormat != null) { return new java.sql.Date(dateFormat.parse(date).getTime()); } - return new java.sql.Date(sdf.parse(date).getTime()); + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); } catch (ParseException e) { throw new JsonParseException(e); } @@ -303,7 +295,7 @@ public class JSON { /** * Gson TypeAdapter for java.util.Date type - * If the dateFormat is null, DateTimeFormatter will be used. + * If the dateFormat is null, ISO8601Utils will be used. */ public static class DateTypeAdapter extends TypeAdapter { @@ -329,7 +321,7 @@ public class JSON { if (dateFormat != null) { value = dateFormat.format(date); } else { - value = date.toInstant().atOffset(ZoneOffset.UTC).format(dtf); + value = ISO8601Utils.format(date, true); } out.value(value); } @@ -348,7 +340,7 @@ public class JSON { if (dateFormat != null) { return dateFormat.parse(date); } - return sdf.parse(date); + return ISO8601Utils.parse(date, new ParsePosition(0)); } catch (ParseException e) { throw new JsonParseException(e); }