From f11b2e6772a66f9c1daa68e3cf7440c5413f45ae Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Thu, 27 Aug 2020 09:38:22 +0800 Subject: [PATCH 01/11] [C][Client][Clang Static Analyzer] Fix memory leak before function returnning (#7302) --- .../src/main/resources/C-libcurl/api-body.mustache | 1 + samples/client/petstore/c/api/PetAPI.c | 4 ++++ samples/client/petstore/c/api/StoreAPI.c | 3 +++ samples/client/petstore/c/api/UserAPI.c | 2 ++ 4 files changed, 10 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache index 463bfddc1e20..3752fcfce1e1 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache @@ -470,6 +470,7 @@ end: {{/formParams}} return elementToReturn; end: + free(localVarPath); return NULL; {{/returnType}} {{^returnType}} diff --git a/samples/client/petstore/c/api/PetAPI.c b/samples/client/petstore/c/api/PetAPI.c index 37ac5b1dc32a..aa3db38496a3 100644 --- a/samples/client/petstore/c/api/PetAPI.c +++ b/samples/client/petstore/c/api/PetAPI.c @@ -271,6 +271,7 @@ PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t * status ) free(localVarPath); return elementToReturn; end: + free(localVarPath); return NULL; } @@ -352,6 +353,7 @@ PetAPI_findPetsByTags(apiClient_t *apiClient, list_t * tags ) free(localVarPath); return elementToReturn; end: + free(localVarPath); return NULL; } @@ -435,6 +437,7 @@ PetAPI_getPetById(apiClient_t *apiClient, long petId ) free(localVarToReplace_petId); return elementToReturn; end: + free(localVarPath); return NULL; } @@ -702,6 +705,7 @@ PetAPI_uploadFile(apiClient_t *apiClient, long petId , char * additionalMetadata free(keyPairForm_file); return elementToReturn; end: + free(localVarPath); return NULL; } diff --git a/samples/client/petstore/c/api/StoreAPI.c b/samples/client/petstore/c/api/StoreAPI.c index 8439ec11d7d2..9d8a539c304c 100644 --- a/samples/client/petstore/c/api/StoreAPI.c +++ b/samples/client/petstore/c/api/StoreAPI.c @@ -134,6 +134,7 @@ StoreAPI_getInventory(apiClient_t *apiClient) free(localVarPath); return elementToReturn; end: + free(localVarPath); return NULL; } @@ -217,6 +218,7 @@ StoreAPI_getOrderById(apiClient_t *apiClient, long orderId ) free(localVarToReplace_orderId); return elementToReturn; end: + free(localVarPath); return NULL; } @@ -291,6 +293,7 @@ StoreAPI_placeOrder(apiClient_t *apiClient, order_t * body ) free(localVarBodyParameters); return elementToReturn; end: + free(localVarPath); return NULL; } diff --git a/samples/client/petstore/c/api/UserAPI.c b/samples/client/petstore/c/api/UserAPI.c index 7c652752fb54..5fdba8bc2a72 100644 --- a/samples/client/petstore/c/api/UserAPI.c +++ b/samples/client/petstore/c/api/UserAPI.c @@ -372,6 +372,7 @@ UserAPI_getUserByName(apiClient_t *apiClient, char * username ) free(localVarToReplace_username); return elementToReturn; end: + free(localVarPath); return NULL; } @@ -477,6 +478,7 @@ UserAPI_loginUser(apiClient_t *apiClient, char * username , char * password ) } return elementToReturn; end: + free(localVarPath); return NULL; } From 8c1f6fcdc14b09a63a533049e8fe279e096be3db Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 27 Aug 2020 11:42:48 +0800 Subject: [PATCH 02/11] [Java][jersey2]Support enum discriminator value in child objects (#7267) * support enum discriminator value in child (java jersey2) * update samples * add tests, use public --- .../codegen/languages/JavaClientCodegen.java | 25 ++++++++++ .../Java/libraries/jersey2/pojo.mustache | 20 ++++++++ ...odels-for-testing-with-http-signature.yaml | 6 +++ .../OpenAPIClientCore/docs/ChildCat.md | 1 + .../OpenAPIClientCore/docs/ChildCatAllOf.md | 1 + .../src/Org.OpenAPITools/Model/ChildCat.cs | 26 +++++++++- .../Org.OpenAPITools/Model/ChildCatAllOf.cs | 25 +++++++++- .../java/jersey2-java8/api/openapi.yaml | 6 +++ .../java/jersey2-java8/docs/ChildCat.md | 9 ++++ .../java/jersey2-java8/docs/ChildCatAllOf.md | 9 ++++ .../openapitools/client/model/ChildCat.java | 50 +++++++++++++++++-- .../client/model/ChildCatAllOf.java | 50 +++++++++++++++++-- .../client/JSONComposedSchemaTest.java | 12 +++++ 13 files changed, 231 insertions(+), 9 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java index a5cb4bc28dac..c841bfb3faab 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java @@ -784,7 +784,32 @@ public Map postProcessModels(Map objs) { // only add JsonNullable and related imports to optional and nullable values addImports |= isOptionalNullable; var.getVendorExtensions().put("x-is-jackson-optional-nullable", isOptionalNullable); + + if (Boolean.TRUE.equals(var.getVendorExtensions().get("x-enum-as-string"))) { + // treat enum string as just string + var.datatypeWithEnum = var.dataType; + + if (StringUtils.isNotEmpty(var.defaultValue)) { // has default value + String defaultValue = var.defaultValue.substring(var.defaultValue.lastIndexOf('.') + 1); + for (Map enumVars : (List>) var.getAllowableValues().get("enumVars")) { + if (defaultValue.equals(enumVars.get("name"))) { + // update default to use the string directly instead of enum string + var.defaultValue = (String) enumVars.get("value"); + } + } + } + + // add import for Set, HashSet + cm.imports.add("Set"); + Map importsSet = new HashMap(); + importsSet.put("import", "java.util.Set"); + imports.add(importsSet); + Map importsHashSet = new HashMap(); + importsHashSet.put("import", "java.util.HashSet"); + imports.add(importsHashSet); + } } + if (addImports) { Map imports2Classnames = new HashMap() {{ put("JsonNullable", "org.openapitools.jackson.nullable.JsonNullable"); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache index 67e753a0a2d0..a32b23d6cb77 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache @@ -18,7 +18,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE {{#vars}} {{#isEnum}} {{^isContainer}} + {{^vendorExtensions.x-enum-as-string}} {{>modelInnerEnum}} + {{/vendorExtensions.x-enum-as-string}} {{/isContainer}} {{#isContainer}} {{#mostInnerItems}} @@ -98,7 +100,19 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE {{#vars}} {{^isReadOnly}} + {{#vendorExtensions.x-enum-as-string}} + public static final Set {{{nameInSnakeCase}}}_VALUES = new HashSet<>(Arrays.asList( + {{#allowableValues}}{{#enumVars}}{{{value}}}{{^-last}}, {{/-last}}{{/enumVars}}{{/allowableValues}} + )); + + {{/vendorExtensions.x-enum-as-string}} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + {{#vendorExtensions.x-enum-as-string}} + if (!{{{nameInSnakeCase}}}_VALUES.contains({{name}})) { + throw new IllegalArgumentException({{name}} + " is invalid. Possible values for {{name}}: " + String.join(", ", {{{nameInSnakeCase}}}_VALUES)); + } + + {{/vendorExtensions.x-enum-as-string}} {{#vendorExtensions.x-is-jackson-optional-nullable}} this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}}); {{/vendorExtensions.x-is-jackson-optional-nullable}} @@ -220,6 +234,12 @@ public class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{{#vendorE {{^isReadOnly}} public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + {{#vendorExtensions.x-enum-as-string}} + if (!{{{nameInSnakeCase}}}_VALUES.contains({{name}})) { + throw new IllegalArgumentException({{name}} + " is invalid. Possible values for {{name}}: " + String.join(", ", {{{nameInSnakeCase}}}_VALUES)); + } + + {{/vendorExtensions.x-enum-as-string}} {{#vendorExtensions.x-is-jackson-optional-nullable}} this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}}); {{/vendorExtensions.x-is-jackson-optional-nullable}} diff --git a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index a0f064611b15..b16f87513080 100644 --- a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -2087,6 +2087,12 @@ components: properties: name: type: string + pet_type: + x-enum-as-string: true + type: string + enum: + - ChildCat + default: ChildCat ArrayOfEnums: type: array items: diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCat.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCat.md index 3942b9d1b9ca..02a1c823c5a7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCat.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCat.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] +**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCatAllOf.md b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCatAllOf.md index b016be9f69e0..18044560aa87 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCatAllOf.md +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/docs/ChildCatAllOf.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] +**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs index fa978d1760b7..55789e18cbbb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs @@ -31,6 +31,25 @@ namespace Org.OpenAPITools.Model [DataContract(Name = "ChildCat")] public partial class ChildCat : ParentPet, IEquatable, IValidatableObject { + /// + /// Defines PetType + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum PetTypeEnum + { + /// + /// Enum ChildCat for value: ChildCat + /// + [EnumMember(Value = "ChildCat")] + ChildCat = 1 + + } + + /// + /// Gets or Sets PetType + /// + [DataMember(Name = "pet_type", EmitDefaultValue = false)] + public PetTypeEnum? PetType { get; set; } /// /// Initializes a new instance of the class. /// @@ -40,10 +59,11 @@ protected ChildCat() { } /// Initializes a new instance of the class. /// /// name. - /// petType (required). - public ChildCat(string name = default(string), string petType = default(string)) : base() + /// petType (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() { this.Name = name; + this.PetType = petType; } /// @@ -62,6 +82,7 @@ public override string ToString() sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -106,6 +127,7 @@ public override int GetHashCode() int hashCode = base.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = hashCode * 59 + this.PetType.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index 05147447b0e4..3214fb19a636 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -31,13 +31,34 @@ namespace Org.OpenAPITools.Model [DataContract(Name = "ChildCat_allOf")] public partial class ChildCatAllOf : IEquatable, IValidatableObject { + /// + /// Defines PetType + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum PetTypeEnum + { + /// + /// Enum ChildCat for value: ChildCat + /// + [EnumMember(Value = "ChildCat")] + ChildCat = 1 + + } + + /// + /// Gets or Sets PetType + /// + [DataMember(Name = "pet_type", EmitDefaultValue = false)] + public PetTypeEnum? PetType { get; set; } /// /// Initializes a new instance of the class. /// /// name. - public ChildCatAllOf(string name = default(string)) + /// petType (default to PetTypeEnum.ChildCat). + public ChildCatAllOf(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) { this.Name = name; + this.PetType = petType; } /// @@ -55,6 +76,7 @@ public override string ToString() var sb = new StringBuilder(); sb.Append("class ChildCatAllOf {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append("}\n"); return sb.ToString(); } @@ -99,6 +121,7 @@ public override int GetHashCode() int hashCode = 41; if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = hashCode * 59 + this.PetType.GetHashCode(); return hashCode; } } diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml b/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml index e09549a0c3d6..f22df8f6bbdf 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml +++ b/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml @@ -2401,6 +2401,12 @@ components: properties: name: type: string + pet_type: + default: ChildCat + enum: + - ChildCat + type: string + x-enum-as-string: true type: object securitySchemes: petstore_auth: diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCat.md b/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCat.md index e6548f036ffb..0715369e4e96 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCat.md +++ b/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCat.md @@ -7,6 +7,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | | [optional] +**petType** | [**String**](#String) | | [optional] + + + +## Enum: String + +Name | Value +---- | ----- +CHILDCAT | "ChildCat" diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCatAllOf.md b/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCatAllOf.md index abd7adedbcc5..f4c3ece5de95 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCatAllOf.md +++ b/samples/openapi3/client/petstore/java/jersey2-java8/docs/ChildCatAllOf.md @@ -7,6 +7,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **String** | | [optional] +**petType** | [**String**](#String) | | [optional] + + + +## Enum: String + +Name | Value +---- | ----- +CHILDCAT | "ChildCat" diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCat.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCat.java index 3e98900120c9..5225511f6798 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCat.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCat.java @@ -32,6 +32,8 @@ import io.swagger.annotations.ApiModelProperty; import org.openapitools.client.model.ChildCatAllOf; import org.openapitools.client.model.ParentPet; +import java.util.Set; +import java.util.HashSet; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.openapitools.client.JSON; @@ -40,7 +42,8 @@ * ChildCat */ @JsonPropertyOrder({ - ChildCat.JSON_PROPERTY_NAME + ChildCat.JSON_PROPERTY_NAME, + ChildCat.JSON_PROPERTY_PET_TYPE }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "pet_type", visible = true) @@ -49,6 +52,9 @@ public class ChildCat extends ParentPet { public static final String JSON_PROPERTY_NAME = "name"; private String name; + public static final String JSON_PROPERTY_PET_TYPE = "pet_type"; + private String petType = "ChildCat"; + public ChildCat name(String name) { this.name = name; @@ -73,6 +79,42 @@ public void setName(String name) { this.name = name; } + + public static final Set PET_TYPE_VALUES = new HashSet<>(Arrays.asList( + "ChildCat" + )); + + public ChildCat petType(String petType) { + if (!PET_TYPE_VALUES.contains(petType)) { + throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); + } + + this.petType = petType; + return this; + } + + /** + * Get petType + * @return petType + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PET_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPetType() { + return petType; + } + + + public void setPetType(String petType) { + if (!PET_TYPE_VALUES.contains(petType)) { + throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); + } + + this.petType = petType; + } + /** * A container for additional, undeclared properties. * This is a holder for any undeclared properties as specified with @@ -123,14 +165,15 @@ public boolean equals(Object o) { return false; } ChildCat childCat = (ChildCat) o; - return Objects.equals(this.name, childCat.name)&& + return Objects.equals(this.name, childCat.name) && + Objects.equals(this.petType, childCat.petType)&& Objects.equals(this.additionalProperties, childCat.additionalProperties) && super.equals(o); } @Override public int hashCode() { - return Objects.hash(name, super.hashCode(), additionalProperties); + return Objects.hash(name, petType, super.hashCode(), additionalProperties); } @@ -140,6 +183,7 @@ public String toString() { sb.append("class ChildCat {\n"); sb.append(" ").append(toIndentedString(super.toString())).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" petType: ").append(toIndentedString(petType)).append("\n"); sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCatAllOf.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCatAllOf.java index 19b5c5108adb..27f4ae52c63b 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCatAllOf.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/ChildCatAllOf.java @@ -24,6 +24,8 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Set; +import java.util.HashSet; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import org.openapitools.client.JSON; @@ -32,13 +34,17 @@ * ChildCatAllOf */ @JsonPropertyOrder({ - ChildCatAllOf.JSON_PROPERTY_NAME + ChildCatAllOf.JSON_PROPERTY_NAME, + ChildCatAllOf.JSON_PROPERTY_PET_TYPE }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class ChildCatAllOf { public static final String JSON_PROPERTY_NAME = "name"; private String name; + public static final String JSON_PROPERTY_PET_TYPE = "pet_type"; + private String petType = "ChildCat"; + public ChildCatAllOf name(String name) { this.name = name; @@ -64,6 +70,42 @@ public void setName(String name) { } + public static final Set PET_TYPE_VALUES = new HashSet<>(Arrays.asList( + "ChildCat" + )); + + public ChildCatAllOf petType(String petType) { + if (!PET_TYPE_VALUES.contains(petType)) { + throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); + } + + this.petType = petType; + return this; + } + + /** + * Get petType + * @return petType + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + @JsonProperty(JSON_PROPERTY_PET_TYPE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getPetType() { + return petType; + } + + + public void setPetType(String petType) { + if (!PET_TYPE_VALUES.contains(petType)) { + throw new IllegalArgumentException(petType + " is invalid. Possible values for petType: " + String.join(", ", PET_TYPE_VALUES)); + } + + this.petType = petType; + } + + /** * Return true if this ChildCat_allOf object is equal to o. */ @@ -76,12 +118,13 @@ public boolean equals(Object o) { return false; } ChildCatAllOf childCatAllOf = (ChildCatAllOf) o; - return Objects.equals(this.name, childCatAllOf.name); + return Objects.equals(this.name, childCatAllOf.name) && + Objects.equals(this.petType, childCatAllOf.petType); } @Override public int hashCode() { - return Objects.hash(name); + return Objects.hash(name, petType); } @@ -90,6 +133,7 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ChildCatAllOf {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" petType: ").append(toIndentedString(petType)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONComposedSchemaTest.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONComposedSchemaTest.java index 1f78f71db78c..3013a0bf533f 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONComposedSchemaTest.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONComposedSchemaTest.java @@ -66,6 +66,18 @@ public void testOneOfSchemaAdditionalProperties() throws Exception { } } + /** + * Test to ensure the setter will throw IllegalArgumentException + */ + @Test(expected = IllegalArgumentException.class) + public void testEnumDiscriminator() throws Exception { + ChildCat cc = new ChildCat(); + cc.setPetType("ChildCat"); + assertEquals("ChildCat", cc.getPetType()); + + cc.setPetType("WrongValue"); + } + /** * Test to ensure the getter will throw ClassCastException */ From b4edfe477a300558624c235f8b5b83f1bc8a02ae Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 27 Aug 2020 11:43:35 +0800 Subject: [PATCH 03/11] [Rust][reqwest] prefix local variables with "local_var" (#7299) * use local_var prefix in rust variables * minor fixes --- .../main/resources/rust/reqwest/api.mustache | 132 +++---- .../rust-reqwest/.openapi-generator/VERSION | 1 - .../petstore-async/src/apis/pet_api.rs | 328 +++++++++--------- .../petstore-async/src/apis/store_api.rs | 142 ++++---- .../petstore-async/src/apis/user_api.rs | 268 +++++++------- .../rust/reqwest/petstore/src/apis/pet_api.rs | 292 ++++++++-------- .../reqwest/petstore/src/apis/store_api.rs | 124 +++---- .../reqwest/petstore/src/apis/user_api.rs | 224 ++++++------ 8 files changed, 755 insertions(+), 756 deletions(-) delete mode 100644 samples/client/petstore/rust-reqwest/.openapi-generator/VERSION diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache index 62d63e1b9b14..fe924ddce19b 100644 --- a/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache @@ -91,18 +91,18 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: &configuration::Configuration, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Result<{{#supportMultipleResponses}}ResponseContent<{{{operationIdCamelCase}}}Success>{{/supportMultipleResponses}}{{^supportMultipleResponses}}{{^returnType}}(){{/returnType}}{{#returnType}}{{{returnType}}}{{/returnType}}{{/supportMultipleResponses}}, Error<{{{operationIdCamelCase}}}Error>> { {{/vendorExtensions.x-group-parameters}} - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}}); - let mut req_builder = client.{{{httpMethod}}}(uri_str.as_str()); + let local_var_uri_str = format!("{}{{{path}}}", configuration.base_path{{#pathParams}}, {{{baseName}}}={{#isString}}crate::apis::urlencode({{/isString}}{{{paramName}}}{{^required}}.unwrap(){{/required}}{{#required}}{{#isNullable}}.unwrap(){{/isNullable}}{{/required}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{#isString}}){{/isString}}{{/pathParams}}); + let mut local_var_req_builder = local_var_client.{{{httpMethod}}}(local_var_uri_str.as_str()); {{#queryParams}} {{#required}} - req_builder = req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isListContainer}}.to_string())]); + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &{{{paramName}}}{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isListContainer}}.to_string())]); {{/required}} {{^required}} - if let Some(ref s) = {{{paramName}}} { - req_builder = req_builder.query(&[("{{{baseName}}}", &s{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isListContainer}}.to_string())]); + if let Some(ref local_var_str) = {{{paramName}}} { + local_var_req_builder = local_var_req_builder.query(&[("{{{baseName}}}", &local_var_str{{#isListContainer}}.into_iter().map(|p| p.to_string()).collect::>().join(","){{/isListContainer}}.to_string())]); } {{/required}} {{/queryParams}} @@ -110,37 +110,37 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: {{#authMethods}} {{#isApiKey}} {{#isKeyInQuery}} - if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); - let val = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + if let Some(ref local_var_apikey) = configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, }; - req_builder = req_builder.query(&[("{{{keyParamName}}}", val)]); + local_var_req_builder = local_var_req_builder.query(&[("{{{keyParamName}}}", local_var_value)]); } {{/isKeyInQuery}} {{/isApiKey}} {{/authMethods}} {{/hasAuthMethods}} - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } {{#hasHeaderParams}} {{#headerParams}} {{#required}} {{^isNullable}} - req_builder = req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); + local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); {{/isNullable}} {{#isNullable}} match {{{paramName}}} { - Some(param_value) => { req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); }, - None => { req_builder = req_builder.header("{{{baseName}}}", ""); }, + Some(local_var_param_value) => { local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", local_var_param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); }, + None => { local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", ""); }, } {{/isNullable}} {{/required}} {{^required}} - if let Some(param_value) = {{{paramName}}} { - req_builder = req_builder.header("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_req_builder = local_var_req_builder.header("{{{baseName}}}", local_var_param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); } {{/required}} {{/headerParams}} @@ -149,55 +149,55 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: {{#authMethods}} {{#isApiKey}} {{#isKeyInHeader}} - if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); - let val = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + if let Some(ref local_var_apikey) = configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, }; - req_builder = req_builder.header("{{{keyParamName}}}", val); + local_var_req_builder = local_var_req_builder.header("{{{keyParamName}}}", local_var_value); }; {{/isKeyInHeader}} {{/isApiKey}} {{#isBasic}} {{#isBasicBasic}} - if let Some(ref auth_conf) = configuration.basic_auth { - req_builder = req_builder.basic_auth(auth_conf.0.to_owned(), auth_conf.1.to_owned()); + if let Some(ref local_var_auth_conf) = configuration.basic_auth { + local_var_req_builder = local_var_req_builder.basic_auth(local_var_auth_conf.0.to_owned(), local_var_auth_conf.1.to_owned()); }; {{/isBasicBasic}} {{#isBasicBearer}} - if let Some(ref token) = configuration.bearer_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.bearer_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; {{/isBasicBearer}} {{/isBasic}} {{#isOAuth}} - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; {{/isOAuth}} {{/authMethods}} {{/hasAuthMethods}} {{#isMultipart}} {{#hasFormParams}} - let mut form = reqwest::multipart::Form::new(); + let mut local_var_form = reqwest::multipart::Form::new(); {{#formParams}} {{#isFile}} {{^supportAsync}} {{#required}} {{^isNullable}} - form = form.file("{{{baseName}}}", {{{paramName}}})?; + local_var_form = local_var_form.file("{{{baseName}}}", {{{paramName}}})?; {{/isNullable}} {{#isNullable}} match {{{paramName}}} { - Some(param_value) => { form = form.file("{{{baseName}}}", param_value)?; }, + Some(local_var_param_value) => { local_var_form = local_var_form.file("{{{baseName}}}", local_var_param_value)?; }, None => { unimplemented!("Required nullable form file param not supported"); }, } {{/isNullable}} {{/required}} {{^required}} - if let Some(param_value) = {{{paramName}}} { - form = form.file("{{{baseName}}}", param_value)?; + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_form = local_var_form.file("{{{baseName}}}", local_var_param_value)?; } {{/required}} {{/supportAsync}} @@ -208,99 +208,99 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: {{^isFile}} {{#required}} {{^isNullable}} - form = form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); + local_var_form = local_var_form.text("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); {{/isNullable}} {{#isNullable}} match {{{paramName}}} { - Some(param_value) => { form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); }, - None => { form = form.text("{{{baseName}}}", ""); }, + Some(local_var_param_value) => { form = form.text("{{{baseName}}}", local_var_param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); }, + None => { local_var_form = local_var_form.text("{{{baseName}}}", ""); }, } {{/isNullable}} {{/required}} {{^required}} - if let Some(param_value) = {{{paramName}}} { - form = form.text("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_form = local_var_form.text("{{{baseName}}}", local_var_param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); } {{/required}} {{/isFile}} {{/formParams}} - req_builder = req_builder.multipart(form); + local_var_req_builder = local_var_req_builder.multipart(local_var_form); {{/hasFormParams}} {{/isMultipart}} {{^isMultipart}} {{#hasFormParams}} - let mut form_params = std::collections::HashMap::new(); + let mut local_var_form_params = std::collections::HashMap::new(); {{#formParams}} {{#isFile}} {{#required}} {{^isNullable}} - form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); {{/isNullable}} {{#isNullable}} match {{{paramName}}} { - Some(param_value) => { form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, + Some(local_var_param_value) => { local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); }, None => { unimplemented!("Required nullable file form param not supported with x-www-form-urlencoded content"); }, } {{/isNullable}} {{/required}} {{^required}} - if let Some(param_value) = {{{paramName}}} { - form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_form_params.insert("{{{baseName}}}", unimplemented!("File form param not supported with x-www-form-urlencoded content")); } {{/required}} {{/isFile}} {{^isFile}} {{#required}} {{^isNullable}} - form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); + local_var_form_params.insert("{{{baseName}}}", {{{paramName}}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); {{/isNullable}} {{#isNullable}} match {{{paramName}}} { - Some(param_value) => { form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); }, - None => { form_params.insert("{{{baseName}}}", ""); }, + Some(local_var_param_value) => { local_var_form_params.insert("{{{baseName}}}", local_var_param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); }, + None => { local_var_form_params.insert("{{{baseName}}}", ""); }, } {{/isNullable}} {{/required}} {{^required}} - if let Some(param_value) = {{{paramName}}} { - form_params.insert("{{{baseName}}}", param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); + if let Some(local_var_param_value) = {{{paramName}}} { + local_var_form_params.insert("{{{baseName}}}", local_var_param_value{{#isListContainer}}.join(","){{/isListContainer}}.to_string()); } {{/required}} {{/isFile}} {{/formParams}} - req_builder = req_builder.form(&form_params); + local_var_req_builder = local_var_req_builder.form(&local_var_form_params); {{/hasFormParams}} {{/isMultipart}} {{#hasBodyParam}} {{#bodyParams}} - req_builder = req_builder.json(&{{{paramName}}}); + local_var_req_builder = local_var_req_builder.json(&{{{paramName}}}); {{/bodyParams}} {{/hasBodyParam}} - let req = req_builder.build()?; - let {{^supportAsync}}mut {{/supportAsync}}resp = client.execute(req){{#supportAsync}}.await{{/supportAsync}}?; + let local_var_req = local_var_req_builder.build()?; + let {{^supportAsync}}mut {{/supportAsync}}local_var_resp = local_var_client.execute(local_var_req){{#supportAsync}}.await{{/supportAsync}}?; - let status = resp.status(); - let content = resp.text(){{#supportAsync}}.await{{/supportAsync}}?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text(){{#supportAsync}}.await{{/supportAsync}}?; - if status.is_success() { + if local_var_status.is_success() { {{^supportMultipleResponses}} {{^returnType}} Ok(()) {{/returnType}} {{#returnType}} - serde_json::from_str(&content).map_err(Error::from) + serde_json::from_str(&local_var_content).map_err(Error::from) {{/returnType}} {{/supportMultipleResponses}} {{#supportMultipleResponses}} - let entity: Option<{{{operationIdCamelCase}}}Success> = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + let local_var_entity: Option<{{{operationIdCamelCase}}}Success> = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) {{/supportMultipleResponses}} } else { - let entity: Option<{{{operationIdCamelCase}}}Error> = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option<{{{operationIdCamelCase}}}Error> = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } diff --git a/samples/client/petstore/rust-reqwest/.openapi-generator/VERSION b/samples/client/petstore/rust-reqwest/.openapi-generator/VERSION deleted file mode 100644 index 479c313e87b9..000000000000 --- a/samples/client/petstore/rust-reqwest/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -4.0.3-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs index d2d1b7c37a94..20644907820c 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/pet_api.rs @@ -212,33 +212,33 @@ pub async fn add_pet(configuration: &configuration::Configuration, params: AddPe let body = params.body; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -248,35 +248,35 @@ pub async fn delete_pet(configuration: &configuration::Configuration, params: De let api_key = params.api_key; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req_builder = client.delete(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(param_value) = api_key { - req_builder = req_builder.header("api_key", param_value.to_string()); + if let Some(local_var_param_value) = api_key { + local_var_req_builder = local_var_req_builder.header("api_key", local_var_param_value.to_string()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -286,33 +286,33 @@ pub async fn find_pets_by_status(configuration: &configuration::Configuration, p let status = params.status; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/findByStatus", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/findByStatus", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - req_builder = req_builder.query(&[("status", &status.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + local_var_req_builder = local_var_req_builder.query(&[("status", &status.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -322,33 +322,33 @@ pub async fn find_pets_by_tags(configuration: &configuration::Configuration, par let tags = params.tags; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/findByTags", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/findByTags", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - req_builder = req_builder.query(&[("tags", &tags.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + local_var_req_builder = local_var_req_builder.query(&[("tags", &tags.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -358,37 +358,37 @@ pub async fn get_pet_by_id(configuration: &configuration::Configuration, params: let pet_id = params.pet_id; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); - let val = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + if let Some(ref local_var_apikey) = configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, }; - req_builder = req_builder.header("api_key", val); + local_var_req_builder = local_var_req_builder.header("api_key", local_var_value); }; - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -397,33 +397,33 @@ pub async fn update_pet(configuration: &configuration::Configuration, params: Up let body = params.body; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet", configuration.base_path); - let mut req_builder = client.put(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet", configuration.base_path); + let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -434,40 +434,40 @@ pub async fn update_pet_with_form(configuration: &configuration::Configuration, let status = params.status; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let mut form_params = std::collections::HashMap::new(); - if let Some(param_value) = name { - form_params.insert("name", param_value.to_string()); + let mut local_var_form_params = std::collections::HashMap::new(); + if let Some(local_var_param_value) = name { + local_var_form_params.insert("name", local_var_param_value.to_string()); } - if let Some(param_value) = status { - form_params.insert("status", param_value.to_string()); + if let Some(local_var_param_value) = status { + local_var_form_params.insert("status", local_var_param_value.to_string()); } - req_builder = req_builder.form(&form_params); + local_var_req_builder = local_var_req_builder.form(&local_var_form_params); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -478,38 +478,38 @@ pub async fn upload_file(configuration: &configuration::Configuration, params: U let file = params.file; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let mut form = reqwest::multipart::Form::new(); - if let Some(param_value) = additional_metadata { - form = form.text("additionalMetadata", param_value.to_string()); + let mut local_var_form = reqwest::multipart::Form::new(); + if let Some(local_var_param_value) = additional_metadata { + local_var_form = local_var_form.text("additionalMetadata", local_var_param_value.to_string()); } // TODO: support file upload for 'file' parameter - req_builder = req_builder.multipart(form); + local_var_req_builder = local_var_req_builder.multipart(local_var_form); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs index 52f40c9ad5c2..df70cd424958 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/store_api.rs @@ -107,29 +107,29 @@ pub async fn delete_order(configuration: &configuration::Configuration, params: let order_id = params.order_id; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=crate::apis::urlencode(order_id)); - let mut req_builder = client.delete(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=crate::apis::urlencode(order_id)); + let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -138,37 +138,37 @@ pub async fn get_inventory(configuration: &configuration::Configuration) -> Resu // unbox the parameters - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/inventory", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/inventory", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); - let val = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + if let Some(ref local_var_apikey) = configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, }; - req_builder = req_builder.header("api_key", val); + local_var_req_builder = local_var_req_builder.header("api_key", local_var_value); }; - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -178,29 +178,29 @@ pub async fn get_order_by_id(configuration: &configuration::Configuration, param let order_id = params.order_id; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -209,30 +209,30 @@ pub async fn place_order(configuration: &configuration::Configuration, params: P let body = params.body; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/order", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/order", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs index 6678d1ec8d0e..7a0375ba9b14 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/apis/user_api.rs @@ -200,30 +200,30 @@ pub async fn create_user(configuration: &configuration::Configuration, params: C let body = params.body; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/user", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -232,30 +232,30 @@ pub async fn create_users_with_array_input(configuration: &configuration::Config let body = params.body; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/createWithArray", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/createWithArray", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -264,30 +264,30 @@ pub async fn create_users_with_list_input(configuration: &configuration::Configu let body = params.body; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/createWithList", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/createWithList", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -297,29 +297,29 @@ pub async fn delete_user(configuration: &configuration::Configuration, params: D let username = params.username; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut req_builder = client.delete(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -328,29 +328,29 @@ pub async fn get_user_by_name(configuration: &configuration::Configuration, para let username = params.username; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -360,31 +360,31 @@ pub async fn login_user(configuration: &configuration::Configuration, params: Lo let password = params.password; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/login", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/login", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - req_builder = req_builder.query(&[("username", &username.to_string())]); - req_builder = req_builder.query(&[("password", &password.to_string())]); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + local_var_req_builder = local_var_req_builder.query(&[("username", &username.to_string())]); + local_var_req_builder = local_var_req_builder.query(&[("password", &password.to_string())]); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -392,29 +392,29 @@ pub async fn logout_user(configuration: &configuration::Configuration) -> Result // unbox the parameters - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/logout", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/logout", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } @@ -425,30 +425,30 @@ pub async fn update_user(configuration: &configuration::Configuration, params: U let body = params.body; - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut req_builder = client.put(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let resp = client.execute(req).await?; + let local_var_req = local_var_req_builder.build()?; + let local_var_resp = local_var_client.execute(local_var_req).await?; - let status = resp.status(); - let content = resp.text().await?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text().await?; - if status.is_success() { - let entity: Option = serde_json::from_str(&content).ok(); - let result = ResponseContent { status, content, entity }; - Ok(result) + if local_var_status.is_success() { + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_result = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Ok(local_var_result) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs index c6715740fc47..301943aa6351 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs @@ -84,264 +84,264 @@ pub enum UploadFileError { pub fn add_pet(configuration: &configuration::Configuration, body: crate::models::Pet) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn delete_pet(configuration: &configuration::Configuration, pet_id: i64, api_key: Option<&str>) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req_builder = client.delete(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(param_value) = api_key { - req_builder = req_builder.header("api_key", param_value.to_string()); + if let Some(local_var_param_value) = api_key { + local_var_req_builder = local_var_req_builder.header("api_key", local_var_param_value.to_string()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } /// Multiple status values can be provided with comma separated strings pub fn find_pets_by_status(configuration: &configuration::Configuration, status: Vec) -> Result, Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/findByStatus", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/findByStatus", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - req_builder = req_builder.query(&[("status", &status.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + local_var_req_builder = local_var_req_builder.query(&[("status", &status.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } /// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. pub fn find_pets_by_tags(configuration: &configuration::Configuration, tags: Vec) -> Result, Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/findByTags", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/findByTags", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - req_builder = req_builder.query(&[("tags", &tags.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + local_var_req_builder = local_var_req_builder.query(&[("tags", &tags.into_iter().map(|p| p.to_string()).collect::>().join(",").to_string())]); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } /// Returns a single pet pub fn get_pet_by_id(configuration: &configuration::Configuration, pet_id: i64) -> Result> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); - let val = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + if let Some(ref local_var_apikey) = configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, }; - req_builder = req_builder.header("api_key", val); + local_var_req_builder = local_var_req_builder.header("api_key", local_var_value); }; - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn update_pet(configuration: &configuration::Configuration, body: crate::models::Pet) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet", configuration.base_path); - let mut req_builder = client.put(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet", configuration.base_path); + let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn update_pet_with_form(configuration: &configuration::Configuration, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let mut form_params = std::collections::HashMap::new(); - if let Some(param_value) = name { - form_params.insert("name", param_value.to_string()); + let mut local_var_form_params = std::collections::HashMap::new(); + if let Some(local_var_param_value) = name { + local_var_form_params.insert("name", local_var_param_value.to_string()); } - if let Some(param_value) = status { - form_params.insert("status", param_value.to_string()); + if let Some(local_var_param_value) = status { + local_var_form_params.insert("status", local_var_param_value.to_string()); } - req_builder = req_builder.form(&form_params); + local_var_req_builder = local_var_req_builder.form(&local_var_form_params); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn upload_file(configuration: &configuration::Configuration, pet_id: i64, additional_metadata: Option<&str>, file: Option) -> Result> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/pet/{petId}/uploadImage", configuration.base_path, petId=pet_id); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref token) = configuration.oauth_access_token { - req_builder = req_builder.bearer_auth(token.to_owned()); + if let Some(ref local_var_token) = configuration.oauth_access_token { + local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let mut form = reqwest::multipart::Form::new(); - if let Some(param_value) = additional_metadata { - form = form.text("additionalMetadata", param_value.to_string()); + let mut local_var_form = reqwest::multipart::Form::new(); + if let Some(local_var_param_value) = additional_metadata { + local_var_form = local_var_form.text("additionalMetadata", local_var_param_value.to_string()); } - if let Some(param_value) = file { - form = form.file("file", param_value)?; + if let Some(local_var_param_value) = file { + local_var_form = local_var_form.file("file", local_var_param_value)?; } - req_builder = req_builder.multipart(form); + local_var_req_builder = local_var_req_builder.multipart(local_var_form); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs index 2474d591dbc1..f7f9fa87b1e0 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/store_api.rs @@ -52,116 +52,116 @@ pub enum PlaceOrderError { /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors pub fn delete_order(configuration: &configuration::Configuration, order_id: &str) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=crate::apis::urlencode(order_id)); - let mut req_builder = client.delete(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=crate::apis::urlencode(order_id)); + let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } /// Returns a map of status codes to quantities pub fn get_inventory(configuration: &configuration::Configuration, ) -> Result<::std::collections::HashMap, Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/inventory", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/inventory", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - if let Some(ref apikey) = configuration.api_key { - let key = apikey.key.clone(); - let val = match apikey.prefix { - Some(ref prefix) => format!("{} {}", prefix, key), - None => key, + if let Some(ref local_var_apikey) = configuration.api_key { + let local_var_key = local_var_apikey.key.clone(); + let local_var_value = match local_var_apikey.prefix { + Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), + None => local_var_key, }; - req_builder = req_builder.header("api_key", val); + local_var_req_builder = local_var_req_builder.header("api_key", local_var_value); }; - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions pub fn get_order_by_id(configuration: &configuration::Configuration, order_id: i64) -> Result> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/order/{orderId}", configuration.base_path, orderId=order_id); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn place_order(configuration: &configuration::Configuration, body: crate::models::Order) -> Result> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/store/order", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/store/order", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs index de5fc2cc4f4e..4aaf235f8ee9 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/user_api.rs @@ -86,217 +86,217 @@ pub enum UpdateUserError { /// This can only be done by the logged in user. pub fn create_user(configuration: &configuration::Configuration, body: crate::models::User) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/user", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn create_users_with_array_input(configuration: &configuration::Configuration, body: Vec) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/createWithArray", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/createWithArray", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn create_users_with_list_input(configuration: &configuration::Configuration, body: Vec) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/createWithList", configuration.base_path); - let mut req_builder = client.post(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/createWithList", configuration.base_path); + let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } /// This can only be done by the logged in user. pub fn delete_user(configuration: &configuration::Configuration, username: &str) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut req_builder = client.delete(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn get_user_by_name(configuration: &configuration::Configuration, username: &str) -> Result> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn login_user(configuration: &configuration::Configuration, username: &str, password: &str) -> Result> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/login", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/login", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - req_builder = req_builder.query(&[("username", &username.to_string())]); - req_builder = req_builder.query(&[("password", &password.to_string())]); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + local_var_req_builder = local_var_req_builder.query(&[("username", &username.to_string())]); + local_var_req_builder = local_var_req_builder.query(&[("password", &password.to_string())]); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { - serde_json::from_str(&content).map_err(Error::from) + if local_var_status.is_success() { + serde_json::from_str(&local_var_content).map_err(Error::from) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } pub fn logout_user(configuration: &configuration::Configuration, ) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/logout", configuration.base_path); - let mut req_builder = client.get(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/logout", configuration.base_path); + let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } /// This can only be done by the logged in user. pub fn update_user(configuration: &configuration::Configuration, username: &str, body: crate::models::User) -> Result<(), Error> { - let client = &configuration.client; + let local_var_client = &configuration.client; - let uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); - let mut req_builder = client.put(uri_str.as_str()); + let local_var_uri_str = format!("{}/user/{username}", configuration.base_path, username=crate::apis::urlencode(username)); + let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); - if let Some(ref user_agent) = configuration.user_agent { - req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone()); + if let Some(ref local_var_user_agent) = configuration.user_agent { + local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } - req_builder = req_builder.json(&body); + local_var_req_builder = local_var_req_builder.json(&body); - let req = req_builder.build()?; - let mut resp = client.execute(req)?; + let local_var_req = local_var_req_builder.build()?; + let mut local_var_resp = local_var_client.execute(local_var_req)?; - let status = resp.status(); - let content = resp.text()?; + let local_var_status = local_var_resp.status(); + let local_var_content = local_var_resp.text()?; - if status.is_success() { + if local_var_status.is_success() { Ok(()) } else { - let entity: Option = serde_json::from_str(&content).ok(); - let error = ResponseContent { status, content, entity }; - Err(Error::ResponseError(error)) + let local_var_entity: Option = serde_json::from_str(&local_var_content).ok(); + let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; + Err(Error::ResponseError(local_var_error)) } } From 892836f772004e775b66e27bb553a41ef3c9e312 Mon Sep 17 00:00:00 2001 From: spacether Date: Thu, 27 Aug 2020 08:07:33 -0700 Subject: [PATCH 04/11] Adds generator unaliasSchema method, uses it to refactor python-experimental (#7274) * Adds generator specific unaliasSchema method * Adds unaliasSchema and hasValidation methods in python-experimental generator * Removes primitive models with no validations, docs, tests, and models * Uses unaliasSchema in getSchemaType and adds todos * Deletes handleMethodResponse and fromResponse * Simplifies fromRequestBody * Removes unneeded handleMethodResponse * Updates javadoc * Updates fromModel * Adds python-exp java test defaultSettingInPrimitiveModelWithValidations, removes model NumberWithValidationsAndDefault form v3 sample spec * Deletes getSimpleTypeDeclaration * Removes straggler file * Deletes hasValidation and modelWillBeMade * Uses super in fromFormProperty * Regenerates samples for python-experimental * Updates postProcessAllModels --- .../openapitools/codegen/DefaultCodegen.java | 33 +- .../PythonClientExperimentalCodegen.java | 762 ++++++------------ .../python/PythonClientExperimentalTest.java | 36 +- 3 files changed, 286 insertions(+), 545 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index 191262d26597..df7ba2d5ada7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -1971,6 +1971,10 @@ public String toOneOfName(List names, ComposedSchema composedSchema) { return "oneOf<" + String.join(",", names) + ">"; } + protected Schema unaliasSchema(Schema schema, Map usedImportMappings) { + return ModelUtils.unaliasSchema(this.openAPI, schema, usedImportMappings); + } + /** * Return a string representation of the schema type, resolving aliasing and references if necessary. * @@ -1978,7 +1982,7 @@ public String toOneOfName(List names, ComposedSchema composedSchema) { * @return the string representation of the schema type. */ protected String getSingleSchemaType(Schema schema) { - Schema unaliasSchema = ModelUtils.unaliasSchema(this.openAPI, schema, importMapping); + Schema unaliasSchema = unaliasSchema(schema, importMapping); if (StringUtils.isNotBlank(unaliasSchema.get$ref())) { // reference to another definition/schema // get the schema/model name from $ref @@ -2216,7 +2220,7 @@ public CodegenModel fromModel(String name, Schema schema) { } // unalias schema - schema = ModelUtils.unaliasSchema(this.openAPI, schema, importMapping); + schema = unaliasSchema(schema, importMapping); if (schema == null) { LOGGER.warn("Schema {} not found", name); return null; @@ -2330,7 +2334,7 @@ public CodegenModel fromModel(String name, Schema schema) { m.interfaces = new ArrayList(); for (Schema interfaceSchema : interfaces) { - interfaceSchema = ModelUtils.unaliasSchema(this.openAPI, interfaceSchema, importMapping); + interfaceSchema = unaliasSchema(interfaceSchema, importMapping); if (StringUtils.isBlank(interfaceSchema.get$ref())) { // primitive type @@ -2991,7 +2995,7 @@ public CodegenProperty fromProperty(String name, Schema p) { LOGGER.debug("debugging fromProperty for " + name + " : " + p); // unalias schema - p = ModelUtils.unaliasSchema(this.openAPI, p, importMapping); + p = unaliasSchema(p, importMapping); CodegenProperty property = CodegenModelFactory.newInstance(CodegenModelType.PROPERTY); @@ -3168,10 +3172,9 @@ public CodegenProperty fromProperty(String name, Schema p) { } else if (ModelUtils.isArraySchema(p)) { // default to string if inner item is undefined ArraySchema arraySchema = (ArraySchema) p; - Schema innerSchema = ModelUtils.unaliasSchema(this.openAPI, getSchemaItems(arraySchema), importMapping); + Schema innerSchema = unaliasSchema(getSchemaItems(arraySchema), importMapping); } else if (ModelUtils.isMapSchema(p)) { - Schema innerSchema = ModelUtils.unaliasSchema(this.openAPI, getAdditionalProperties(p), - importMapping); + Schema innerSchema = unaliasSchema(getAdditionalProperties(p), importMapping); if (innerSchema == null) { LOGGER.error("Undefined map inner type for `{}`. Default to String.", p.getName()); innerSchema = new StringSchema().description("//TODO automatically added by openapi-generator due to undefined type"); @@ -3251,7 +3254,7 @@ public CodegenProperty fromProperty(String name, Schema p) { itemName = property.name; } ArraySchema arraySchema = (ArraySchema) p; - Schema innerSchema = ModelUtils.unaliasSchema(this.openAPI, getSchemaItems(arraySchema), importMapping); + Schema innerSchema = unaliasSchema(getSchemaItems(arraySchema), importMapping); CodegenProperty cp = fromProperty(itemName, innerSchema); updatePropertyForArray(property, cp); } else if (ModelUtils.isMapSchema(p)) { @@ -3263,8 +3266,7 @@ public CodegenProperty fromProperty(String name, Schema p) { property.maxItems = p.getMaxProperties(); // handle inner property - Schema innerSchema = ModelUtils.unaliasSchema(this.openAPI, getAdditionalProperties(p), - importMapping); + Schema innerSchema = unaliasSchema(getAdditionalProperties(p), importMapping); if (innerSchema == null) { LOGGER.error("Undefined map inner type for `{}`. Default to String.", p.getName()); innerSchema = new StringSchema().description("//TODO automatically added by openapi-generator due to undefined type"); @@ -3504,7 +3506,7 @@ protected void handleMethodResponse(Operation operation, CodegenOperation op, ApiResponse methodResponse, Map importMappings) { - Schema responseSchema = ModelUtils.unaliasSchema(this.openAPI, ModelUtils.getSchemaFromResponse(methodResponse), importMappings); + Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(methodResponse), importMapping); if (responseSchema != null) { CodegenProperty cm = fromProperty("response", responseSchema); @@ -3908,8 +3910,7 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { } Schema responseSchema; if (this.openAPI != null && this.openAPI.getComponents() != null) { - responseSchema = ModelUtils.unaliasSchema(this.openAPI, ModelUtils.getSchemaFromResponse(response), - importMapping); + responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(response), importMapping); } else { // no model/alias defined responseSchema = ModelUtils.getSchemaFromResponse(response); } @@ -4150,7 +4151,7 @@ public CodegenParameter fromParameter(Parameter parameter, Set imports) } if (parameterSchema != null) { - parameterSchema = ModelUtils.unaliasSchema(this.openAPI, parameterSchema); + parameterSchema = unaliasSchema(parameterSchema, Collections.emptyMap()); if (parameterSchema == null) { LOGGER.warn("warning! Schema not found for parameter \"" + parameter.getName() + "\", using String"); parameterSchema = new StringSchema().description("//TODO automatically added by openapi-generator due to missing type definition."); @@ -4690,7 +4691,7 @@ protected void addImport(CodegenModel m, String type) { private Map unaliasPropertySchema(Map properties) { if (properties != null) { for (String key : properties.keySet()) { - properties.put(key, ModelUtils.unaliasSchema(this.openAPI, properties.get(key), importMapping())); + properties.put(key, unaliasSchema(properties.get(key), importMapping())); } } @@ -5815,7 +5816,7 @@ public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set return codegenParameter; } - private void addBodyModelSchema(CodegenParameter codegenParameter, String name, Schema schema, Set imports, String bodyParameterName, boolean forceSimpleRef) { + protected void addBodyModelSchema(CodegenParameter codegenParameter, String name, Schema schema, Set imports, String bodyParameterName, boolean forceSimpleRef) { CodegenModel codegenModel = null; if (StringUtils.isNotBlank(name)) { schema.setName(name); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java index 941c5d11d87b..f156a44e6e99 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonClientExperimentalCodegen.java @@ -17,19 +17,16 @@ package org.openapitools.codegen.languages; import io.swagger.v3.core.util.Json; -import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.*; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.MediaType; import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.RequestBody; -import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.security.SecurityScheme; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; import org.openapitools.codegen.CodegenDiscriminator.MappedModel; -import org.openapitools.codegen.examples.ExampleGenerator; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.utils.ModelUtils; import org.openapitools.codegen.utils.ProcessUtils; @@ -225,6 +222,83 @@ public String getName() { return "python-experimental"; } + @Override + protected Schema unaliasSchema(Schema schema, Map usedImportMappings) { + Map allSchemas = ModelUtils.getSchemas(openAPI); + if (allSchemas == null || allSchemas.isEmpty()) { + // skip the warning as the spec can have no model defined + //LOGGER.warn("allSchemas cannot be null/empty in unaliasSchema. Returned 'schema'"); + return schema; + } + + if (schema != null && StringUtils.isNotEmpty(schema.get$ref())) { + String simpleRef = ModelUtils.getSimpleRef(schema.get$ref()); + if (usedImportMappings.containsKey(simpleRef)) { + LOGGER.debug("Schema unaliasing of {} omitted because aliased class is to be mapped to {}", simpleRef, usedImportMappings.get(simpleRef)); + return schema; + } + Schema ref = allSchemas.get(simpleRef); + Boolean hasValidation = ( + ref.getMaxItems() != null || + ref.getMinLength() != null || + ref.getMinItems() != null || + ref.getMultipleOf() != null || + ref.getPattern() != null || + ref.getMaxLength() != null || + ref.getMinimum() != null || + ref.getMaximum() != null || + ref.getExclusiveMaximum() != null || + ref.getExclusiveMinimum() != null || + ref.getUniqueItems() != null + ); + if (ref == null) { + once(LOGGER).warn("{} is not defined", schema.get$ref()); + return schema; + } else if (ref.getEnum() != null && !ref.getEnum().isEmpty()) { + // top-level enum class + return schema; + } else if (ModelUtils.isArraySchema(ref)) { + if (ModelUtils.isGenerateAliasAsModel(ref)) { + return schema; // generate a model extending array + } else { + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), + usedImportMappings); + } + } else if (ModelUtils.isComposedSchema(ref)) { + return schema; + } else if (ModelUtils.isMapSchema(ref)) { + if (ref.getProperties() != null && !ref.getProperties().isEmpty()) // has at least one property + return schema; // treat it as model + else { + if (ModelUtils.isGenerateAliasAsModel(ref)) { + return schema; // generate a model extending map + } else { + // treat it as a typical map + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), + usedImportMappings); + } + } + } else if (ModelUtils.isObjectSchema(ref)) { // model + if (ref.getProperties() != null && !ref.getProperties().isEmpty()) { // has at least one property + return schema; + } else { // free form object (type: object) + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), + usedImportMappings); + } + } else if (hasValidation) { + // non object non array non map schemas that have validations + // are returned so we can generate those schemas as models + // we do this to: + // - preserve the validations in that model class in python + // - use those validations when we use this schema in composed oneOf schemas + return schema; + } else { + return unaliasSchema(allSchemas.get(ModelUtils.getSimpleRef(schema.get$ref())), usedImportMappings); + } + } + return schema; + } + public String pythonDate(Object dateValue) { String strValue = null; if (dateValue instanceof OffsetDateTime) { @@ -329,57 +403,58 @@ public Map postProcessOperationsWithModels(Map o return objs; } - /** + /*** * Override with special post-processing for all models. + * we have a custom version of this method to: + * - remove any primitive models that do not contain validations + * these models are unaliased as inline definitions wherever the spec has them as refs + * this means that the generated client does not use these models + * because they are not used we do not write them + * - fix the model imports, go from model name to the full import string with toModelImport + globalImportFixer + * + * @param objs a map going from the model name to a object hoding the model info + * @return the updated objs */ - @SuppressWarnings({"static-method", "unchecked"}) + @Override public Map postProcessAllModels(Map objs) { super.postProcessAllModels(objs); - // loop through all models and delete ones where type!=object and the model has no validations and enums - // we will remove them because they are not needed - Map modelSchemasToRemove = new HashMap(); - - for (Object objModel: objs.values()) { - HashMap hmModel = (HashMap) objModel; - List> models = (List>) hmModel.get("models"); - for (Map model : models) { - CodegenModel cm = (CodegenModel) model.get("model"); - - // remove model if it is a primitive with no validations - if (cm.isEnum || cm.isAlias) { - Schema modelSchema = ModelUtils.getSchema(this.openAPI, cm.name); - CodegenProperty modelProperty = fromProperty("_value", modelSchema); - if (!modelProperty.isEnum && !modelProperty.hasValidation && !cm.isArrayModel) { - // remove these models because they are aliases and do not have any enums or validations - modelSchemasToRemove.put(cm.name, modelSchema); - continue; + List modelsToRemove = new ArrayList<>(); + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + for (String schemaName: allDefinitions.keySet()) { + Schema refSchema = new Schema().$ref("#/components/schemas/"+schemaName); + Schema unaliasedSchema = unaliasSchema(refSchema, importMapping); + String modelName = toModelName(schemaName); + if (unaliasedSchema.get$ref() == null) { + modelsToRemove.add(modelName); + } else { + HashMap objModel = (HashMap) objs.get(modelName); + List> models = (List>) objModel.get("models"); + for (Map model : models) { + CodegenModel cm = (CodegenModel) model.get("model"); + String[] importModelNames = cm.imports.toArray(new String[0]); + cm.imports.clear(); + for (String importModelName : importModelNames) { + cm.imports.add(toModelImport(importModelName)); + String globalImportFixer = "globals()['" + importModelName + "'] = " + importModelName; + cm.imports.add(globalImportFixer); } } - - // fix model imports - if (cm.imports.size() == 0) { - continue; - } - String[] modelNames = cm.imports.toArray(new String[0]); - cm.imports.clear(); - for (String modelName : modelNames) { - cm.imports.add(toModelImport(modelName)); - String globalImportFixer = "globals()['" + modelName + "'] = " + modelName; - cm.imports.add(globalImportFixer); - } } } - // Remove modelSchemasToRemove models from objs - for (String modelName : modelSchemasToRemove.keySet()) { + for (String modelName : modelsToRemove) { objs.remove(modelName); } + return objs; } /** * Convert OAS Property object to Codegen Property object + * We have a custom version of this method to always set allowableValues.enumVars on all enum variables + * Together with unaliasSchema this sets primitive types with validations as models + * This method is used by fromResponse * * @param name name of the property * @param p OAS property object @@ -387,12 +462,17 @@ public Map postProcessAllModels(Map objs) { */ @Override public CodegenProperty fromProperty(String name, Schema p) { - // we have a custom version of this function to always set allowableValues.enumVars on all enum variables - CodegenProperty result = super.fromProperty(name, p); - if (result.isEnum) { - updateCodegenPropertyEnum(result); + CodegenProperty cp = super.fromProperty(name, p); + if (cp.isEnum) { + updateCodegenPropertyEnum(cp); + } + if (cp.isPrimitiveType && p.get$ref() != null) { + cp.complexType = cp.dataType; } - return result; + if (cp.isListContainer && cp.complexType == null && cp.mostInnerItems.complexType != null) { + cp.complexType = cp.mostInnerItems.complexType; + } + return cp; } /** @@ -439,167 +519,69 @@ public void updateCodegenPropertyEnum(CodegenProperty var) { // overwriting defaultValue omitted from here } - @Override - public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { - CodegenParameter result = super.fromRequestBody(body, imports, bodyParameterName); - // if we generated a model with a non-object type because it has validations or enums, - // make sure that the datatype of that body parameter refers to our model class - Content content = body.getContent(); - Set keySet = content.keySet(); - Object[] keyArray = (Object[]) keySet.toArray(); - MediaType mediaType = content.get(keyArray[0]); - Schema schema = mediaType.getSchema(); - String ref = schema.get$ref(); - if (ref == null) { - return result; - } - String modelName = ModelUtils.getSimpleRef(ref); - // the result lacks validation info so we need to make a CodegenProperty from the schema to check - // if we have validation and enum info exists - Schema realSchema = ModelUtils.getSchema(this.openAPI, modelName); - CodegenProperty modelProp = fromProperty("body", realSchema); - if (modelProp.isPrimitiveType && (modelProp.hasValidation || modelProp.isEnum)) { - String simpleDataType = result.dataType; - result.dataType = toModelName(modelName); - result.baseType = result.dataType; - } - return result; - } - - /** - * Convert OAS Response object to Codegen Response object - * - * @param responseCode HTTP response code - * @param response OAS Response object - * @return Codegen Response object - */ - @Override - public CodegenResponse fromResponse(String responseCode, ApiResponse response) { - // if a response points at a model whose type != object and it has validations and/or enums, then we will - // generate the model, and response.baseType must be the name - // of the model. Point responses at models if the model is python class type ModelSimple - // When we serialize/deserialize ModelSimple models, validations and enums will be checked. - Schema responseSchema; - if (this.openAPI != null && this.openAPI.getComponents() != null) { - responseSchema = ModelUtils.unaliasSchema(this.openAPI, ModelUtils.getSchemaFromResponse(response), importMapping); - } else { // no model/alias defined - responseSchema = ModelUtils.getSchemaFromResponse(response); - } - - String newBaseType = null; - if (responseSchema != null) { - CodegenProperty cp = fromProperty("response", responseSchema); - if (cp.complexType != null) { - String modelName = cp.complexType; - Schema modelSchema = ModelUtils.getSchema(this.openAPI, modelName); - if (modelSchema != null && !"object".equals(modelSchema.getType())) { - CodegenProperty modelProp = fromProperty("response", modelSchema); - if (modelProp.isEnum == true || modelProp.hasValidation == true) { - // this model has validations and/or enums so we will generate it - newBaseType = modelName; - } - } - } else { - if (cp.isEnum == true || cp.hasValidation == true) { - // this model has validations and/or enums so we will generate it - Schema sc = ModelUtils.getSchemaFromResponse(response); - newBaseType = toModelName(ModelUtils.getSimpleRef(sc.get$ref())); - } - } - } - - CodegenResponse result = super.fromResponse(responseCode, response); - if (newBaseType != null) { - result.dataType = newBaseType; - // baseType is used to set the link to the model .md documentation - result.baseType = newBaseType; - } - - return result; - } - - /** - * Set op's returnBaseType, returnType, examples etc. + /*** + * We have a custom version of this method to produce links to models when they are + * primitive type (not map, not array, not object) and include validations or are enums * - * @param operation endpoint Operation - * @param schemas a map of the schemas in the openapi spec - * @param op endpoint CodegenOperation - * @param methodResponse the default ApiResponse for the endpoint + * @param body requesst body + * @param imports import collection + * @param bodyParameterName body parameter name + * @return the resultant CodegenParameter */ @Override - public void handleMethodResponse(Operation operation, - Map schemas, - CodegenOperation op, - ApiResponse methodResponse) { - handleMethodResponse(operation, schemas, op, methodResponse, Collections.emptyMap()); + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { + CodegenParameter cp = super.fromRequestBody(body, imports, bodyParameterName); + Schema schema = ModelUtils.getSchemaFromRequestBody(body); + if (schema.get$ref() == null) { + return cp; + } + Schema unaliasedSchema = unaliasSchema(schema, importMapping); + CodegenProperty unaliasedProp = fromProperty("body", unaliasedSchema); + Boolean dataTypeMismatch = !cp.dataType.equals(unaliasedProp.dataType); + Boolean baseTypeMismatch = !cp.baseType.equals(unaliasedProp.complexType) && unaliasedProp.complexType != null; + if (dataTypeMismatch || baseTypeMismatch) { + cp.dataType = unaliasedProp.dataType; + cp.baseType = unaliasedProp.complexType; + } + return cp; } - /** - * Set op's returnBaseType, returnType, examples etc. + /*** + * Adds the body model schema to the body parameter + * We have a custom version of this method so we can flip forceSimpleRef + * to True based upon the results of unaliasSchema + * With this customization, we ensure that when schemas are passed to getSchemaType + * - if they have ref in them they are a model + * - if they do not have ref in them they are not a model * - * @param operation endpoint Operation - * @param schemas a map of the schemas in the openapi spec - * @param op endpoint CodegenOperation - * @param methodResponse the default ApiResponse for the endpoint - * @param importMappings mappings of external types to be omitted by unaliasing + * @param codegenParameter the body parameter + * @param name model schema ref key in components + * @param schema the model schema (not refed) + * @param imports collection of imports + * @param bodyParameterName body parameter name + * @param forceSimpleRef if true use a model reference */ @Override - protected void handleMethodResponse(Operation operation, - Map schemas, - CodegenOperation op, - ApiResponse methodResponse, - Map importMappings) { - // we have a custom version of this method to handle endpoints that return models where - // type != object the model has validations and/or enums - // we do this by invoking our custom fromResponse method to create defaultResponse - // which we then use to set op.returnType and op.returnBaseType - CodegenResponse defaultResponse = fromResponse("defaultResponse", methodResponse); - Schema responseSchema = ModelUtils.unaliasSchema(this.openAPI, ModelUtils.getSchemaFromResponse(methodResponse), importMappings); - - if (responseSchema != null) { - op.returnBaseType = defaultResponse.baseType; - - // generate examples - String exampleStatusCode = "200"; - for (String key : operation.getResponses().keySet()) { - if (operation.getResponses().get(key) == methodResponse && !key.equals("default")) { - exampleStatusCode = key; - } - } - op.examples = new ExampleGenerator(schemas, this.openAPI).generateFromResponseSchema(exampleStatusCode, responseSchema, getProducesInfo(this.openAPI, operation)); - op.defaultResponse = toDefaultValue(responseSchema); - op.returnType = defaultResponse.dataType; - op.hasReference = schemas.containsKey(op.returnBaseType); - - // lookup discriminator - Schema schema = schemas.get(op.returnBaseType); - if (schema != null) { - CodegenModel cmod = fromModel(op.returnBaseType, schema); - op.discriminator = cmod.discriminator; - } - - if (defaultResponse.isListContainer) { - op.isListContainer = true; - } else if (defaultResponse.isMapContainer) { - op.isMapContainer = true; - } else { - op.returnSimpleType = true; - } - if (languageSpecificPrimitives().contains(op.returnBaseType) || op.returnBaseType == null) { - op.returnTypeIsPrimitive = true; + protected void addBodyModelSchema(CodegenParameter codegenParameter, String name, Schema schema, Set imports, String bodyParameterName, boolean forceSimpleRef) { + if (name != null) { + Schema bodySchema = new Schema().$ref("#/components/schemas/" + name); + Schema unaliased = unaliasSchema(bodySchema, importMapping); + if (unaliased.get$ref() != null) { + forceSimpleRef = true; } } - addHeaders(methodResponse, op.responseHeaders); + super.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, forceSimpleRef); + } - /** - * Return the sanitized variable name for enum - * - * @param value enum variable name - * @param datatype data type - * @return the sanitized variable name for enum - */ + /** + * Return the sanitized variable name for enum + * + * @param value enum variable name + * @param datatype data type + * @return the sanitized variable name for enum + */ public String toEnumVarName(String value, String datatype) { // our enum var names are keys in a python dict, so change spaces to underscores if (value.length() == 0) { @@ -710,175 +692,62 @@ protected void addParentContainer(CodegenModel model, String name, Schema schema /** * Convert OAS Model object to Codegen Model object + * We have a custom version of this method so we can: + * - set the correct regex values for requiredVars + optionalVars + * - set model.defaultValue and model.hasRequired per the three use cases defined in this method * * @param name the name of the model - * @param schema OAS Model object + * @param sc OAS Model object * @return Codegen Model object */ @Override - public CodegenModel fromModel(String name, Schema schema) { - // we have a custom version of this function so we can produce - // models for components whose type != object and which have validations and enums - // this ensures that: - // - endpoint (operation) responses with validations and type!=(object or array) - // - oneOf $ref components with validations and type!=(object or array) - // when endpoints receive payloads of these models - // that they will be converted into instances of these models - Map propertyToModelName = new HashMap(); - Map propertiesMap = schema.getProperties(); - if (propertiesMap != null) { - for (Map.Entry entry : propertiesMap.entrySet()) { - String schemaPropertyName = entry.getKey(); - String pythonPropertyName = toVarName(schemaPropertyName); - Schema propertySchema = entry.getValue(); - String ref = propertySchema.get$ref(); - if (ref == null) { - continue; - } - Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, propertySchema); - String refType = refSchema.getType(); - if (refType == null || refType.equals("object")) { - continue; - } - CodegenProperty modelProperty = fromProperty("_fake_name", refSchema); - if (modelProperty.isEnum == true || modelProperty.hasValidation == false) { - continue; - } - String modelName = ModelUtils.getSimpleRef(ref); - propertyToModelName.put(pythonPropertyName, toModelName(modelName)); - } - } - CodegenModel result = super.fromModel(name, schema); - - // have oneOf point to the correct model - if (ModelUtils.isComposedSchema(schema)) { - ComposedSchema cs = (ComposedSchema) schema; - Map importCounts = new HashMap(); - List oneOfSchemas = cs.getOneOf(); - if (oneOfSchemas != null) { - for (int i = 0; i < oneOfSchemas.size(); i++) { - Schema oneOfSchema = oneOfSchemas.get(i); - String languageType = getTypeDeclaration(oneOfSchema); - String ref = oneOfSchema.get$ref(); - if (ref == null) { - Integer currVal = importCounts.getOrDefault(languageType, 0); - importCounts.put(languageType, currVal+1); - continue; - } - Schema refSchema = ModelUtils.getReferencedSchema(this.openAPI, oneOfSchema); - String refType = refSchema.getType(); - if (refType == null || refType.equals("object")) { - Integer currVal = importCounts.getOrDefault(languageType, 0); - importCounts.put(languageType, currVal+1); - continue; - } - - CodegenProperty modelProperty = fromProperty("_oneOfSchema", refSchema); - if (modelProperty.isEnum == true) { - Integer currVal = importCounts.getOrDefault(languageType, 0); - importCounts.put(languageType, currVal+1); - continue; - } - - languageType = getTypeDeclaration(refSchema); - if (modelProperty.hasValidation == false) { - Integer currVal = importCounts.getOrDefault(languageType, 0); - importCounts.put(languageType, currVal+1); - continue; - } - Integer currVal = importCounts.getOrDefault(languageType, 0); - importCounts.put(languageType, currVal); - String modelName = toModelName(ModelUtils.getSimpleRef(ref)); - result.imports.add(modelName); - result.oneOf.add(modelName); - currVal = importCounts.getOrDefault(modelName, 0); - importCounts.put(modelName, currVal+1); - } - } - for (Map.Entry entry : importCounts.entrySet()) { - String importName = entry.getKey(); - Integer importCount = entry.getValue(); - if (importCount == 0) { - result.oneOf.remove(importName); - } - } - } - - // this block handles models which have the python base class ModelSimple - // which are responsible for storing validations, enums, and an unnamed value - Schema modelSchema = ModelUtils.getSchema(this.openAPI, result.name); - CodegenProperty modelProperty = fromProperty("_value", modelSchema); - - Boolean isPythonModelSimpleModel = (result.isEnum || result.isArrayModel || result.isAlias && modelProperty.hasValidation); - if (isPythonModelSimpleModel) { - // In python, classes which inherit from our ModelSimple class store one value, - // like a str, int, list and extra data about that value like validations and enums - - if (result.isEnum) { - // if there is only one allowed value then we know that it should be set, so value is optional - // -> hasRequired = false - // if there are more than one allowed value then value is positional and required so - // -> hasRequired = true - ArrayList values = (ArrayList) result.allowableValues.get("values"); - if (values != null && values.size() > 1) { - result.hasRequired = true; - } - - if (modelProperty.defaultValue != null && result.defaultValue == null) { - result.defaultValue = modelProperty.defaultValue; - } - } else { - if (result.defaultValue == null) { - result.hasRequired = true; - } - } + public CodegenModel fromModel(String name, Schema sc) { + CodegenModel cm = super.fromModel(name, sc); + if (cm.requiredVars.size() > 0 && (cm.oneOf.size() > 0 || cm.anyOf.size() > 0)) { + addNullDefaultToOneOfAnyOfReqProps(sc, cm); } - // fix all property references to ModelSimple models, make those properties non-primitive and - // set their dataType and complexType to the model name, so documentation will refer to the correct model - // set regex values, before it was only done on model.vars - // NOTE: this is done for models of type != object which are not enums and have validations ArrayList> listOfLists = new ArrayList>(); - listOfLists.add(result.vars); - listOfLists.add(result.allVars); - listOfLists.add(result.requiredVars); - listOfLists.add(result.optionalVars); - listOfLists.add(result.readOnlyVars); - listOfLists.add(result.readWriteVars); + listOfLists.add(cm.requiredVars); + listOfLists.add(cm.optionalVars); for (List cpList : listOfLists) { for (CodegenProperty cp : cpList) { - // set regex values, before it was only done on model.vars - postProcessModelProperty(result, cp); - // fix references to non-object models - if (!propertyToModelName.containsKey(cp.name)) { - continue; - } - cp.isPrimitiveType = false; - String modelName = propertyToModelName.get(cp.name); - cp.complexType = modelName; - cp.dataType = modelName; - cp.isEnum = false; - cp.hasValidation = false; - result.imports.add(modelName); + // sets regex values + postProcessModelProperty(cm, cp); } } - - // if a class has a property of type self, remove the self import from imports - if (result.imports.contains(result.classname)) { - result.imports.remove(result.classname); - } - - if (result.requiredVars.size() > 0 && (result.oneOf.size() > 0 || result.anyOf.size() > 0)) { - addNullDefaultToOneOfAnyOfReqProps(schema, result); - } - - return result; + Boolean isNotPythonModelSimpleModel = (ModelUtils.isComposedSchema(sc) || ModelUtils.isObjectSchema(sc) || ModelUtils.isMapSchema(sc)); + if (isNotPythonModelSimpleModel) { + return cm; + } + // Use cases for default values / enums of length one + // 1. no default exists + // schema does not contain default + // cm.defaultValue unset, cm.hasRequired = true + // 2. server has a default + // schema contains default + // cm.defaultValue set, cm.hasRequired = true + // different value here to differentiate between use case 3 below + // This defaultValue is used in the client docs only and is not sent to the server + // 3. only one value is allowed in an enum + // schema does not contain default + // cm.defaultValue set, cm.hasRequired = false + // because we know what value needs to be set so the user doesn't need to input it + // This defaultValue is used in the client and is sent to the server + String defaultValue = toDefaultValue(sc); + if (sc.getDefault() == null && defaultValue == null) { + cm.hasRequired = true; + } else if (sc.getDefault() != null) { + cm.defaultValue = defaultValue; + cm.hasRequired = true; + } else if (defaultValue != null && cm.defaultValue == null) { + cm.defaultValue = defaultValue; + cm.hasRequired = false; + } + return cm; } /** - * returns the OpenAPI type for the property. Use getAlias to handle $ref of primitive type - * We have a custom version of this function because for composed schemas we also want to return the model name - * In DefaultCodegen.java it returns a name built off of individual allOf/anyOf/oneOf which is not what - * python-experimental needs. Python-experimental needs the name of the composed schema + * Returns the python type for the property. * * @param schema property schema * @return string presentation of the type @@ -886,102 +755,24 @@ public CodegenModel fromModel(String name, Schema schema) { @SuppressWarnings("static-method") @Override public String getSchemaType(Schema schema) { - if (schema instanceof ComposedSchema) { // composed schema - Schema unaliasSchema = ModelUtils.unaliasSchema(this.openAPI, schema, importMapping); - String ref = unaliasSchema.get$ref(); - if (ref != null) { - String schemaName = ModelUtils.getSimpleRef(unaliasSchema.get$ref()); - if (StringUtils.isNotEmpty(schemaName) && importMapping.containsKey(schemaName)) { - return schemaName; - } - return getAlias(schemaName); - } else { - // we may have be processing the component schema rather than a schema with a $ref - // to a component schema - // so loop through component schemas and use the found one's name if we match - Map schemas = ModelUtils.getSchemas(openAPI); - for (String thisSchemaName : schemas.keySet()) { - Schema thisSchema = schemas.get(thisSchemaName); - if (!ModelUtils.isComposedSchema(thisSchema)) { - continue; - } - if (thisSchema == unaliasSchema) { - if (importMapping.containsKey(thisSchemaName)) { - return thisSchemaName; - } - return getAlias(thisSchemaName); - } - } - LOGGER.warn("Error obtaining the datatype from ref:" + unaliasSchema.get$ref() + ". Default to 'object'"); - return "object"; - } - } String openAPIType = getSingleSchemaType(schema); if (typeMapping.containsKey(openAPIType)) { String type = typeMapping.get(openAPIType); - if (languageSpecificPrimitives.contains(type)) { - return type; - } - } else { - return toModelName(openAPIType); + return type; } - return openAPIType; + return toModelName(openAPIType); } public String getModelName(Schema sc) { - Boolean thisModelWillBeMade = modelWillBeMade(sc); - Map schemas = ModelUtils.getSchemas(openAPI); - for (String thisSchemaName : schemas.keySet()) { - Schema thisSchema = schemas.get(thisSchemaName); - if (thisSchema == sc && thisModelWillBeMade) { - return toModelName(thisSchemaName); + if (sc.get$ref() != null) { + Schema unaliasedSchema = unaliasSchema(sc, importMapping); + if (unaliasedSchema.get$ref() != null) { + return toModelName(ModelUtils.getSimpleRef(sc.get$ref())); } } return null; } - /** - * Output the type declaration of the property - * - * @param schema property schema - * @return a string presentation of the property type - */ - public String getSimpleTypeDeclaration(Schema schema) { - String oasType = getSchemaType(schema); - if (typeMapping.containsKey(oasType)) { - return typeMapping.get(oasType); - } - return oasType; - } - - public Boolean modelWillBeMade(Schema s) { - // only invoke this on $refed schemas - if (ModelUtils.isComposedSchema(s) || ModelUtils.isObjectSchema(s) || ModelUtils.isArraySchema(s) || ModelUtils.isMapSchema(s)) { - return true; - } - List enums = s.getEnum(); - if (enums != null && !enums.isEmpty()) { - return true; - } - Boolean hasValidation = ( - s.getMaxItems() != null || - s.getMinLength() != null || - s.getMinItems() != null || - s.getMultipleOf() != null || - s.getPattern() != null || - s.getMaxLength() != null || - s.getMinimum() != null || - s.getMaximum() != null || - s.getExclusiveMaximum() != null || - s.getExclusiveMinimum() != null || - s.getUniqueItems() != null - ); - if (hasValidation) { - return true; - } - return false; - } - /** * Return a string representation of the Python types for the specified OAS schema. * Primitive types in the OAS specification are implemented in Python using the corresponding @@ -1011,8 +802,8 @@ private String getTypeString(Schema p, String prefix, String suffix, List allDefinitions = ModelUtils.getSchemas(this.openAPI); String ref = ModelUtils.getSimpleRef(schema.get$ref()); - if (allDefinitions != null) { - Schema refSchema = allDefinitions.get(ref); - if (null == refSchema) { - return fullPrefix + "None" + closeChars; - } else { - String refModelName = getModelName(refSchema); - return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine); - } - } else { - LOGGER.warn("allDefinitions not defined in toExampleValue!\n"); + Schema refSchema = allDefinitions.get(ref); + if (null == refSchema) { + LOGGER.warn("Unable to find referenced schema "+schema.get$ref()+"\n"); + return fullPrefix + "None" + closeChars; } + String refModelName = getModelName(schema); + return toExampleValueRecursive(refModelName, refSchema, objExample, indentationLevel, prefix, exampleLine); } else if (ModelUtils.isNullType(schema) || isAnyTypeSchema(schema)) { // The 'null' type is allowed in OAS 3.1 and above. It is not supported by OAS 3.0.x, // though this tooling supports it. @@ -1537,92 +1323,12 @@ public void setParameterExampleValue(CodegenParameter codegenParameter, RequestB */ @Override public CodegenParameter fromFormProperty(String name, Schema propertySchema, Set imports) { - CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); - - LOGGER.debug("Debugging fromFormProperty {}: {}", name, propertySchema); - CodegenProperty codegenProperty = fromProperty(name, propertySchema); - - ModelUtils.syncValidationProperties(propertySchema, codegenProperty); - - codegenParameter.isFormParam = Boolean.TRUE; - codegenParameter.baseName = codegenProperty.baseName; - codegenParameter.paramName = toParamName((codegenParameter.baseName)); - codegenParameter.baseType = codegenProperty.baseType; - codegenParameter.dataType = codegenProperty.dataType; - codegenParameter.dataFormat = codegenProperty.dataFormat; - codegenParameter.description = escapeText(codegenProperty.description); - codegenParameter.unescapedDescription = codegenProperty.getDescription(); - codegenParameter.jsonSchema = Json.pretty(propertySchema); - codegenParameter.defaultValue = codegenProperty.getDefaultValue(); - - if (codegenProperty.getVendorExtensions() != null && !codegenProperty.getVendorExtensions().isEmpty()) { - codegenParameter.vendorExtensions = codegenProperty.getVendorExtensions(); - } - if (propertySchema.getRequired() != null && !propertySchema.getRequired().isEmpty() && propertySchema.getRequired().contains(codegenProperty.baseName)) { - codegenParameter.required = Boolean.TRUE; - } - - // non-array/map - updateCodegenPropertyEnum(codegenProperty); - codegenParameter.isEnum = codegenProperty.isEnum; - codegenParameter._enum = codegenProperty._enum; - codegenParameter.allowableValues = codegenProperty.allowableValues; - - if (codegenProperty.isEnum) { - codegenParameter.datatypeWithEnum = codegenProperty.datatypeWithEnum; - codegenParameter.enumName = codegenProperty.enumName; - } - - if (codegenProperty.items != null && codegenProperty.items.isEnum) { - codegenParameter.items = codegenProperty.items; - codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; - } - - // import - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); - } - - // validation - // handle maximum, minimum properly for int/long by removing the trailing ".0" - if (ModelUtils.isIntegerSchema(propertySchema)) { - codegenParameter.maximum = propertySchema.getMaximum() == null ? null : String.valueOf(propertySchema.getMaximum().longValue()); - codegenParameter.minimum = propertySchema.getMinimum() == null ? null : String.valueOf(propertySchema.getMinimum().longValue()); - } else { - codegenParameter.maximum = propertySchema.getMaximum() == null ? null : String.valueOf(propertySchema.getMaximum()); - codegenParameter.minimum = propertySchema.getMinimum() == null ? null : String.valueOf(propertySchema.getMinimum()); - } - - codegenParameter.exclusiveMaximum = propertySchema.getExclusiveMaximum() == null ? false : propertySchema.getExclusiveMaximum(); - codegenParameter.exclusiveMinimum = propertySchema.getExclusiveMinimum() == null ? false : propertySchema.getExclusiveMinimum(); - codegenParameter.maxLength = propertySchema.getMaxLength(); - codegenParameter.minLength = propertySchema.getMinLength(); - codegenParameter.pattern = toRegularExpression(propertySchema.getPattern()); - codegenParameter.maxItems = propertySchema.getMaxItems(); - codegenParameter.minItems = propertySchema.getMinItems(); - codegenParameter.uniqueItems = propertySchema.getUniqueItems() == null ? false : propertySchema.getUniqueItems(); - codegenParameter.multipleOf = propertySchema.getMultipleOf(); - - // exclusive* are noop without corresponding min/max - if (codegenParameter.maximum != null || codegenParameter.minimum != null || - codegenParameter.maxLength != null || codegenParameter.minLength != null || - codegenParameter.maxItems != null || codegenParameter.minItems != null || - codegenParameter.pattern != null || codegenParameter.multipleOf != null) { - codegenParameter.hasValidation = true; - } - - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + CodegenParameter cp = super.fromFormProperty(name, propertySchema, imports); Parameter p = new Parameter(); p.setSchema(propertySchema); - p.setName(codegenParameter.paramName); - setParameterExampleValue(codegenParameter, p); - // setParameterExampleValue(codegenParameter); - // set nullable - setParameterNullable(codegenParameter, codegenProperty); - - //TODO collectionFormat for form parameter not yet supported - //codegenParameter.collectionFormat = getCollectionFormat(propertySchema); - return codegenParameter; + p.setName(cp.paramName); + setParameterExampleValue(cp, p); + return cp; } /** diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java index 258320fbc4ca..5412564359fc 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientExperimentalTest.java @@ -21,7 +21,8 @@ import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.media.*; import io.swagger.v3.parser.util.SchemaTypeUtil; -import java.time.OffsetDateTime; +import java.math.BigDecimal; +import java.util.Arrays; import org.openapitools.codegen.*; import org.openapitools.codegen.languages.PythonClientExperimentalCodegen; import org.openapitools.codegen.utils.ModelUtils; @@ -341,4 +342,37 @@ public void importSpecialModelNameTest() { Assert.assertEquals(importValue, "from models.special_model_name import SpecialModelName"); } + @Test(description = "format imports of models containing special characters") + public void defaultSettingInPrimitiveModelWithValidations() { + final PythonClientExperimentalCodegen codegen = new PythonClientExperimentalCodegen(); + + OpenAPI openAPI = TestUtils.createOpenAPI(); + final Schema noDefault = new ArraySchema() + .type("number") + .minimum(new BigDecimal("10")); + final Schema hasDefault = new Schema() + .type("number") + .minimum(new BigDecimal("10")); + hasDefault.setDefault("15.0"); + final Schema noDefaultEumLengthOne = new Schema() + .type("number") + .minimum(new BigDecimal("10")); + noDefaultEumLengthOne.setEnum(Arrays.asList("15.0")); + openAPI.getComponents().addSchemas("noDefaultModel", noDefault); + openAPI.getComponents().addSchemas("hasDefaultModel", hasDefault); + openAPI.getComponents().addSchemas("noDefaultEumLengthOneModel", noDefaultEumLengthOne); + codegen.setOpenAPI(openAPI); + + final CodegenModel noDefaultModel = codegen.fromModel("noDefaultModel", noDefault); + Assert.assertEquals(noDefaultModel.defaultValue, null); + Assert.assertEquals(noDefaultModel.hasRequired, true); + + final CodegenModel hasDefaultModel = codegen.fromModel("hasDefaultModel", hasDefault); + Assert.assertEquals(hasDefaultModel.defaultValue, "15.0"); + Assert.assertEquals(hasDefaultModel.hasRequired, true); + + final CodegenModel noDefaultEumLengthOneModel = codegen.fromModel("noDefaultEumLengthOneModel", noDefaultEumLengthOne); + Assert.assertEquals(noDefaultEumLengthOneModel.defaultValue, "15.0"); + Assert.assertEquals(noDefaultEumLengthOneModel.hasRequired, false); + } } From 26c17c5774a02c8cea3c16ba2b11ca20ea860211 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 27 Aug 2020 23:13:56 +0800 Subject: [PATCH 05/11] [Java] remove deprecated jackson classes (#7304) * [java/resttemplate] Generate valid code if no Authentication implementations present Take the logic used to decide which instances to add to the authentications map and re-use to not import classes or offer non-functional util methods * parameterize formParams fixes #5782 * replace use of ISO8601DateFormat and ISO8601Utils with StdDateFormat fixes #5779 * add constructor to intialise calendar * Revert "[java/resttemplate] Generate valid code if no Authentication implementations present" This reverts commit 6e450907bae1d831a4a8c9b66f6b707424f0a39a. * Revert "parameterize formParams" This reverts commit 7a26ce5dd21ce147ed33728cd0091a29175367a4. * also override single arg parse method to avoid throwing exception * also override single arg parse method to avoid throwing exception * update samples * update samples * fix jersey1 tests * fix jersey2 test * update resteasy dependencies * fix java jersey2 oas3 tests * use java8 in springboot-beanvalidation Co-authored-by: Jon Freedman --- bin/configs/spring-boot-beanvalidation.yaml | 2 +- .../resources/Java/RFC3339DateFormat.mustache | 37 ++- .../JavaJaxRS/RFC3339DateFormat.mustache | 39 ++- .../resteasy/RFC3339DateFormat.mustache | 39 ++- .../resources/JavaJaxRS/resteasy/pom.mustache | 8 +- .../spring-boot/RFC3339DateFormat.mustache | 32 +- .../spring-mvc/RFC3339DateFormat.mustache | 32 +- .../RFC3339DateFormat.mustache | 39 ++- .../java-pkmst/RFC3339DateFormat.mustache | 32 +- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../openapitools/client/ApiClientTest.java | 4 +- .../client/RFC3339DateFormat.java | 37 ++- .../openapitools/client/ApiClientTest.java | 2 +- .../org/openapitools/client/JSONTest.java | 6 +- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../client/RFC3339DateFormat.java | 37 ++- .../org/openapitools/client/JSONTest.java | 6 +- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../petstore/jaxrs-resteasy/default/pom.xml | 8 +- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../petstore/jaxrs-resteasy/joda/pom.xml | 8 +- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../openapitools/api/RFC3339DateFormat.java | 39 ++- .../configuration/RFC3339DateFormat.java | 32 +- .../configuration/RFC3339DateFormat.java | 32 +- .../configuration/RFC3339DateFormat.java | 32 +- .../.openapi-generator/FILES | 2 - .../springboot-beanvalidation/pom.xml | 9 +- .../org/openapitools/OpenAPI2SpringBoot.java | 3 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- .../org/openapitools/api/AnotherFakeApi.java | 22 +- .../api/AnotherFakeApiController.java | 39 +-- .../java/org/openapitools/api/FakeApi.java | 118 ++++++-- .../openapitools/api/FakeApiController.java | 276 +----------------- .../api/FakeClassnameTestApi.java | 22 +- .../api/FakeClassnameTestApiController.java | 39 +-- .../java/org/openapitools/api/PetApi.java | 99 ++++++- .../openapitools/api/PetApiController.java | 179 +----------- .../java/org/openapitools/api/StoreApi.java | 56 +++- .../openapitools/api/StoreApiController.java | 98 +------ .../java/org/openapitools/api/UserApi.java | 62 +++- .../openapitools/api/UserApiController.java | 137 +-------- .../CustomInstantDeserializer.java | 232 --------------- .../configuration/JacksonConfiguration.java | 23 -- .../OpenAPIDocumentationConfig.java | 5 +- .../model/AdditionalPropertiesClass.java | 16 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../openapitools/model/ArrayOfNumberOnly.java | 2 +- .../org/openapitools/model/ArrayTest.java | 6 +- .../org/openapitools/model/EnumArrays.java | 2 +- .../model/FileSchemaTestClass.java | 2 +- .../org/openapitools/model/FormatTest.java | 4 +- .../java/org/openapitools/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 4 +- .../java/org/openapitools/model/Order.java | 2 +- .../main/java/org/openapitools/model/Pet.java | 4 +- .../openapitools/model/TypeHolderDefault.java | 2 +- .../openapitools/model/TypeHolderExample.java | 2 +- .../java/org/openapitools/model/XmlItem.java | 18 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- .../org/openapitools/RFC3339DateFormat.java | 32 +- 81 files changed, 1564 insertions(+), 1446 deletions(-) delete mode 100644 samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java delete mode 100644 samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/JacksonConfiguration.java diff --git a/bin/configs/spring-boot-beanvalidation.yaml b/bin/configs/spring-boot-beanvalidation.yaml index 6b39c85dc941..573d8e283b55 100644 --- a/bin/configs/spring-boot-beanvalidation.yaml +++ b/bin/configs/spring-boot-beanvalidation.yaml @@ -4,7 +4,7 @@ library: spring-boot inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml templateDir: modules/openapi-generator/src/main/resources/JavaSpring additionalProperties: - java8: "false" + java8: true useBeanValidation: true artifactId: spring-boot-beanvalidation hideGenerationTimestamp: "true" diff --git a/modules/openapi-generator/src/main/resources/Java/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/Java/RFC3339DateFormat.mustache index 16fd2a495a75..cacd793e738a 100644 --- a/modules/openapi-generator/src/main/resources/Java/RFC3339DateFormat.mustache +++ b/modules/openapi-generator/src/main/resources/Java/RFC3339DateFormat.mustache @@ -1,21 +1,44 @@ {{>licenseInfo}} package {{invokerPackage}}; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/RFC3339DateFormat.mustache index 061e000f5a24..76ede2dc0061 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/RFC3339DateFormat.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/RFC3339DateFormat.mustache @@ -1,19 +1,38 @@ package {{apiPackage}}; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/RFC3339DateFormat.mustache index 11dc552692c4..8373f57b5479 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/RFC3339DateFormat.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/RFC3339DateFormat.mustache @@ -1,19 +1,38 @@ package {{invokerPackage}}; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache index d6389cce0962..71362596698c 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache @@ -98,13 +98,13 @@ org.jboss.resteasy jaxrs-api - ${resteasy-version} + 3.0.12.Final provided org.jboss.resteasy resteasy-validator-provider-11 - ${resteasy-version} + 3.6.3.SP1 provided @@ -129,7 +129,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.9.9 + 2.11.2 joda-time @@ -190,7 +190,7 @@ 1.5.22 9.2.9.v20150224 - 3.0.11.Final + 3.13.0.Final 1.6.3 4.8.1 2.5 diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache index d5dff8ac6314..b1a5cb59e550 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-boot/RFC3339DateFormat.mustache @@ -1,22 +1,38 @@ package {{basePackage}}; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache index 597120b5b239..84897b70d400 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-mvc/RFC3339DateFormat.mustache @@ -1,22 +1,38 @@ package {{configPackage}}; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-msf4j-server/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/java-msf4j-server/RFC3339DateFormat.mustache index 061e000f5a24..76ede2dc0061 100644 --- a/modules/openapi-generator/src/main/resources/java-msf4j-server/RFC3339DateFormat.mustache +++ b/modules/openapi-generator/src/main/resources/java-msf4j-server/RFC3339DateFormat.mustache @@ -1,19 +1,38 @@ package {{apiPackage}}; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-pkmst/RFC3339DateFormat.mustache b/modules/openapi-generator/src/main/resources/java-pkmst/RFC3339DateFormat.mustache index afe24ed9aba9..b1a5cb59e550 100644 --- a/modules/openapi-generator/src/main/resources/java-pkmst/RFC3339DateFormat.mustache +++ b/modules/openapi-generator/src/main/resources/java-pkmst/RFC3339DateFormat.mustache @@ -1,20 +1,38 @@ package {{basePackage}}; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/feign/feign10x/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/feign/feign10x/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/feign/feign10x/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/feign/feign10x/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/jersey1/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java index 682690f049d5..dadb65fa1c54 100644 --- a/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey1/src/test/java/org/openapitools/client/ApiClientTest.java @@ -21,9 +21,9 @@ public void setup() { @Test public void testParseAndFormatDate() { // default date format - String dateStr = "2015-11-07T03:49:09.356Z"; - assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); + String dateStr = "2015-11-07T03:49:09.356+00:00"; assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); + assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T02:49:09.356-01:00"))); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java index 1fcc0bca7f48..90a3758eba24 100644 --- a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/ApiClientTest.java @@ -21,7 +21,7 @@ public void setup() { @Test public void testParseAndFormatDate() { // default date format - String dateStr = "2015-11-07T03:49:09.356Z"; + String dateStr = "2015-11-07T03:49:09.356+00:00"; assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356+00:00"))); assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T03:49:09.356Z"))); assertEquals(dateStr, apiClient.formatDate(apiClient.parseDate("2015-11-07T05:49:09.356+02:00"))); diff --git a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java index 2ce38ae2f69a..26c568d1956a 100644 --- a/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java @@ -47,7 +47,7 @@ public void testRFC3339DateFormatDate() throws Exception { StringBuffer sb = new StringBuffer(); String s = df.format(date); System.out.println("DATE: " + s); - assertEquals("2011-01-18T00:00:00.000Z", s); + assertEquals("2011-01-18T00:00:00.000+00:00", s); } { String dateStr = "2011-01-18 00:00:00.0"; @@ -58,7 +58,7 @@ public void testRFC3339DateFormatDate() throws Exception { RFC3339DateFormat df = new RFC3339DateFormat(); StringBuffer sb = new StringBuffer(); String s = df.format(date); - assertEquals("2011-01-18T08:00:00.000Z", s); + assertEquals("2011-01-18T08:00:00.000+00:00", s); } } @@ -87,4 +87,4 @@ public void testSchemaWithSpecialCharacters() throws Exception { assertNotNull(o); assertEquals((long)12345, (long)o.get$SpecialPropertyName()); } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 82a86b83afc1..f7ec336d257d 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java index 9509fd089812..07d7e782b0da 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -12,21 +12,44 @@ package org.openapitools.client; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java index 2ce38ae2f69a..26c568d1956a 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/test/java/org/openapitools/client/JSONTest.java @@ -47,7 +47,7 @@ public void testRFC3339DateFormatDate() throws Exception { StringBuffer sb = new StringBuffer(); String s = df.format(date); System.out.println("DATE: " + s); - assertEquals("2011-01-18T00:00:00.000Z", s); + assertEquals("2011-01-18T00:00:00.000+00:00", s); } { String dateStr = "2011-01-18 00:00:00.0"; @@ -58,7 +58,7 @@ public void testRFC3339DateFormatDate() throws Exception { RFC3339DateFormat df = new RFC3339DateFormat(); StringBuffer sb = new StringBuffer(); String s = df.format(date); - assertEquals("2011-01-18T08:00:00.000Z", s); + assertEquals("2011-01-18T08:00:00.000+00:00", s); } } @@ -87,4 +87,4 @@ public void testSchemaWithSpecialCharacters() throws Exception { assertNotNull(o); assertEquals((long)12345, (long)o.get$SpecialPropertyName()); } -} \ No newline at end of file +} diff --git a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/default/pom.xml b/samples/server/petstore/jaxrs-resteasy/default/pom.xml index a80ce0132f3c..7299a876f0c6 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/default/pom.xml @@ -98,13 +98,13 @@ org.jboss.resteasy jaxrs-api - ${resteasy-version} + 3.0.12.Final provided org.jboss.resteasy resteasy-validator-provider-11 - ${resteasy-version} + 3.6.3.SP1 provided @@ -129,7 +129,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.9.9 + 2.11.2 joda-time @@ -188,7 +188,7 @@ 1.5.22 9.2.9.v20150224 - 3.0.11.Final + 3.13.0.Final 1.6.3 4.8.1 2.5 diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/joda/pom.xml b/samples/server/petstore/jaxrs-resteasy/joda/pom.xml index 451da95535b3..d159ec9cca7c 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/joda/pom.xml @@ -98,13 +98,13 @@ org.jboss.resteasy jaxrs-api - ${resteasy-version} + 3.0.12.Final provided org.jboss.resteasy resteasy-validator-provider-11 - ${resteasy-version} + 3.6.3.SP1 provided @@ -129,7 +129,7 @@ com.fasterxml.jackson.datatype jackson-datatype-joda - 2.9.9 + 2.11.2 joda-time @@ -188,7 +188,7 @@ 1.5.22 9.2.9.v20150224 - 3.0.11.Final + 3.13.0.Final 1.6.3 4.8.1 2.5 diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs/jersey1-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs/jersey1/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/RFC3339DateFormat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/RFC3339DateFormat.java index b471837701d9..3c9230efefe2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/RFC3339DateFormat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/RFC3339DateFormat.java @@ -1,19 +1,38 @@ package org.openapitools.api; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; -public class RFC3339DateFormat extends ISO8601DateFormat { +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); - // Same as ISO8601DateFormat but serializing milliseconds. - @Override - public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; - } + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java index c546ba4fcea7..697c27391a5c 100644 --- a/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java +++ b/samples/server/petstore/spring-mvc-j8-async/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools.configuration; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java index c546ba4fcea7..697c27391a5c 100644 --- a/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java +++ b/samples/server/petstore/spring-mvc-j8-localdatetime/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools.configuration; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java index c546ba4fcea7..697c27391a5c 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools.configuration; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES index 4bb76c23b2a2..61420a325e38 100644 --- a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES @@ -15,9 +15,7 @@ src/main/java/org/openapitools/api/StoreApi.java src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java src/main/java/org/openapitools/api/UserApiController.java -src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java src/main/java/org/openapitools/configuration/HomeController.java -src/main/java/org/openapitools/configuration/JacksonConfiguration.java src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java src/main/java/org/openapitools/model/AdditionalPropertiesAnyType.java src/main/java/org/openapitools/model/AdditionalPropertiesArray.java diff --git a/samples/server/petstore/springboot-beanvalidation/pom.xml b/samples/server/petstore/springboot-beanvalidation/pom.xml index 6536e609c6cf..eda7fc97d6f0 100644 --- a/samples/server/petstore/springboot-beanvalidation/pom.xml +++ b/samples/server/petstore/springboot-beanvalidation/pom.xml @@ -6,7 +6,7 @@ spring-boot-beanvalidation 1.0.0 - 1.7 + 1.8 ${java.version} ${java.version} 2.8.0 @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.5.12.RELEASE + 2.0.1.RELEASE src/main/java @@ -54,9 +54,8 @@ 2.2.11 - com.github.joschi.jackson - jackson-datatype-threetenbp - 2.8.4 + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 org.openapitools diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/OpenAPI2SpringBoot.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/OpenAPI2SpringBoot.java index b7af36b6bbd3..7cad28eed8ac 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/OpenAPI2SpringBoot.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/OpenAPI2SpringBoot.java @@ -10,7 +10,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication @ComponentScan(basePackages = {"org.openapitools", "org.openapitools.api" , "org.openapitools.configuration"}) @@ -39,7 +38,7 @@ public int getExitCode() { @Bean public WebMvcConfigurer webConfigurer() { - return new WebMvcConfigurerAdapter() { + return new WebMvcConfigurer() { /*@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java index 07b6801beb07..44f3e9bb93f2 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -7,20 +7,28 @@ import org.openapitools.model.Client; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * PATCH /another-fake/dummy : To test special tags * To test special tags and operation ID starting with number @@ -36,6 +44,18 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java index 50393d3230ad..d8efcca7f8a4 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -1,25 +1,9 @@ package org.openapitools.api; -import org.openapitools.model.Client; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -32,24 +16,9 @@ public AnotherFakeApiController(NativeWebRequest request) { this.request = request; } - /** - * PATCH /another-fake/dummy : To test special tags - * To test special tags and operation ID starting with number - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see AnotherFakeApi#call123testSpecialTags - */ - public ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"client\" : \"client\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java index f2f112c57500..11a5cf7b551a 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java @@ -8,29 +8,37 @@ import java.math.BigDecimal; import org.openapitools.model.Client; import org.openapitools.model.FileSchemaTestClass; -import org.threeten.bp.LocalDate; +import java.time.LocalDate; import java.util.Map; import org.openapitools.model.ModelApiResponse; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; import org.openapitools.model.OuterComposite; import org.springframework.core.io.Resource; import org.openapitools.model.User; import org.openapitools.model.XmlItem; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") public interface FakeApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /fake/create_xml_item : creates an XmlItem * this route creates an XmlItem @@ -45,7 +53,10 @@ public interface FakeApi { value = "/fake/create_xml_item", consumes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" } ) - ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem); + default ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -62,7 +73,10 @@ public interface FakeApi { value = "/fake/outer/boolean", produces = { "*/*" } ) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body); + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -79,7 +93,19 @@ public interface FakeApi { value = "/fake/outer/composite", produces = { "*/*" } ) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body); + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { + String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }"; + ApiUtil.setExampleResponse(request, "*/*", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -96,7 +122,10 @@ public interface FakeApi { value = "/fake/outer/number", produces = { "*/*" } ) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body); + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -113,7 +142,10 @@ public interface FakeApi { value = "/fake/outer/string", produces = { "*/*" } ) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body); + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -130,7 +162,10 @@ public interface FakeApi { value = "/fake/body-with-file-schema", consumes = { "application/json" } ) - ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body); + default ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -147,7 +182,10 @@ public interface FakeApi { value = "/fake/body-with-query-params", consumes = { "application/json" } ) - ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -165,7 +203,19 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -199,16 +249,19 @@ public interface FakeApi { value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback); + default ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /fake : To test enum parameters * To test enum parameters * - * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -225,7 +278,10 @@ public interface FakeApi { value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString); + default ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -246,7 +302,10 @@ public interface FakeApi { @DeleteMapping( value = "/fake" ) - ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group); + default ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -262,7 +321,10 @@ public interface FakeApi { value = "/fake/inline-additionalProperties", consumes = { "application/json" } ) - ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param); + default ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -279,7 +341,10 @@ public interface FakeApi { value = "/fake/jsonFormData", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2); + default ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -299,7 +364,10 @@ public interface FakeApi { @PutMapping( value = "/fake/test-query-paramters" ) - ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context); + default ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -323,6 +391,18 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "multipart/form-data" } ) - ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata); + default ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java index 75f81592a13b..c4b88419aabe 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApiController.java @@ -1,35 +1,9 @@ package org.openapitools.api; -import java.math.BigDecimal; -import org.openapitools.model.Client; -import org.openapitools.model.FileSchemaTestClass; -import org.threeten.bp.LocalDate; -import java.util.Map; -import org.openapitools.model.ModelApiResponse; -import org.threeten.bp.OffsetDateTime; -import org.openapitools.model.OuterComposite; -import org.springframework.core.io.Resource; -import org.openapitools.model.User; -import org.openapitools.model.XmlItem; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -42,251 +16,9 @@ public FakeApiController(NativeWebRequest request) { this.request = request; } - /** - * POST /fake/create_xml_item : creates an XmlItem - * this route creates an XmlItem - * - * @param xmlItem XmlItem Body (required) - * @return successful operation (status code 200) - * @see FakeApi#createXmlItem - */ - public ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/boolean - * Test serialization of outer boolean types - * - * @param body Input boolean as post body (optional) - * @return Output boolean (status code 200) - * @see FakeApi#fakeOuterBooleanSerialize - */ - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/composite - * Test serialization of object with outer number type - * - * @param body Input composite as post body (optional) - * @return Output composite (status code 200) - * @see FakeApi#fakeOuterCompositeSerialize - */ - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { - String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }"; - ApiUtil.setExampleResponse(request, "*/*", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/number - * Test serialization of outer number types - * - * @param body Input number as post body (optional) - * @return Output number (status code 200) - * @see FakeApi#fakeOuterNumberSerialize - */ - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/string - * Test serialization of outer string types - * - * @param body Input string as post body (optional) - * @return Output string (status code 200) - * @see FakeApi#fakeOuterStringSerialize - */ - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /fake/body-with-file-schema - * For this test, the body for this request much reference a schema named `File`. - * - * @param body (required) - * @return Success (status code 200) - * @see FakeApi#testBodyWithFileSchema - */ - public ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /fake/body-with-query-params - * - * @param query (required) - * @param body (required) - * @return Success (status code 200) - * @see FakeApi#testBodyWithQueryParams - */ - public ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PATCH /fake : To test \"client\" model - * To test \"client\" model - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see FakeApi#testClientModel - */ - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"client\" : \"client\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake : Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @return Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see FakeApi#testEndpointParameters - */ - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /fake : To test enum parameters - * To test enum parameters - * - * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<String>()) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<String>()) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param enumFormStringArray Form parameter enum test (string array) (optional, default to $) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @return Invalid request (status code 400) - * or Not found (status code 404) - * @see FakeApi#testEnumParameters - */ - public ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * DELETE /fake : Fake endpoint to test group parameters (optional) - * Fake endpoint to test group parameters (optional) - * - * @param requiredStringGroup Required String in group parameters (required) - * @param requiredBooleanGroup Required Boolean in group parameters (required) - * @param requiredInt64Group Required Integer in group parameters (required) - * @param stringGroup String in group parameters (optional) - * @param booleanGroup Boolean in group parameters (optional) - * @param int64Group Integer in group parameters (optional) - * @return Someting wrong (status code 400) - * @see FakeApi#testGroupParameters - */ - public ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/inline-additionalProperties : test inline additionalProperties - * - * @param param request body (required) - * @return successful operation (status code 200) - * @see FakeApi#testInlineAdditionalProperties - */ - public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /fake/jsonFormData : test json serialization of form data - * - * @param param field1 (required) - * @param param2 field2 (required) - * @return successful operation (status code 200) - * @see FakeApi#testJsonFormData - */ - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /fake/test-query-paramters - * To test the collection format in query parameters - * - * @param pipe (required) - * @param ioutil (required) - * @param http (required) - * @param url (required) - * @param context (required) - * @return Success (status code 200) - * @see FakeApi#testQueryParameterCollectionFormat - */ - public ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/{petId}/uploadImageWithRequiredFile : uploads an image (required) - * - * @param petId ID of pet to update (required) - * @param requiredFile file to upload (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @return successful operation (status code 200) - * @see FakeApi#uploadFileWithRequiredFile - */ - public ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 723fc9f62ac5..5742965028b0 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -7,20 +7,28 @@ import org.openapitools.model.Client; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * PATCH /fake_classname_test : To test class name in snake case * To test class name in snake case @@ -38,6 +46,18 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 237a76382362..85458b255da5 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -1,25 +1,9 @@ package org.openapitools.api; -import org.openapitools.model.Client; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -32,24 +16,9 @@ public FakeClassnameTestApiController(NativeWebRequest request) { this.request = request; } - /** - * PATCH /fake_classname_test : To test class name in snake case - * To test class name in snake case - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see FakeClassnameTestApi#testClassname - */ - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"client\" : \"client\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java index 7ab2f6e9d5f7..51080bb7d32b 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java @@ -10,20 +10,28 @@ import org.springframework.core.io.Resource; import java.util.Set; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "the pet API") public interface PetApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /pet : Add a new pet to the store * @@ -44,7 +52,10 @@ public interface PetApi { value = "/pet", consumes = { "application/json", "application/xml" } ) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); + default ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -67,7 +78,10 @@ public interface PetApi { @DeleteMapping( value = "/pet/{petId}" ) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + default ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -91,7 +105,24 @@ public interface PetApi { value = "/pet/findByStatus", produces = { "application/xml", "application/json" } ) - ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); + default ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -116,7 +147,24 @@ public interface PetApi { value = "/pet/findByTags", produces = { "application/xml", "application/json" } ) - ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags); + default ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -139,7 +187,24 @@ public interface PetApi { value = "/pet/{petId}", produces = { "application/xml", "application/json" } ) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); + default ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -166,7 +231,10 @@ public interface PetApi { value = "/pet", consumes = { "application/json", "application/xml" } ) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); + default ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -189,7 +257,10 @@ public interface PetApi { value = "/pet/{petId}", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status); + default ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -213,6 +284,18 @@ public interface PetApi { produces = { "application/json" }, consumes = { "multipart/form-data" } ) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file); + default ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java index 6621ae38e156..e72c57e3cbec 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApiController.java @@ -1,28 +1,9 @@ package org.openapitools.api; -import org.openapitools.model.ModelApiResponse; -import org.openapitools.model.Pet; -import org.springframework.core.io.Resource; -import java.util.Set; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -35,161 +16,9 @@ public PetApiController(NativeWebRequest request) { this.request = request; } - /** - * POST /pet : Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return successful operation (status code 200) - * or Invalid input (status code 405) - * @see PetApi#addPet - */ - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * DELETE /pet/{petId} : Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return successful operation (status code 200) - * or Invalid pet value (status code 400) - * @see PetApi#deletePet - */ - public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /pet/findByStatus : Finds Pets by status - * Multiple status values can be provided with comma separated strings - * - * @param status Status values that need to be considered for filter (required) - * @return successful operation (status code 200) - * or Invalid status value (status code 400) - * @see PetApi#findPetsByStatus - */ - public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 doggie aeiou aeiou "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /pet/findByTags : Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @param tags Tags to filter by (required) - * @return successful operation (status code 200) - * or Invalid tag value (status code 400) - * @deprecated - * @see PetApi#findPetsByTags - */ - public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 doggie aeiou aeiou "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /pet/{petId} : Find pet by ID - * Returns a single pet - * - * @param petId ID of pet to return (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Pet not found (status code 404) - * @see PetApi#getPetById - */ - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 doggie aeiou aeiou "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /pet : Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Pet not found (status code 404) - * or Validation exception (status code 405) - * @see PetApi#updatePet - */ - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /pet/{petId} : Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return Invalid input (status code 405) - * @see PetApi#updatePetWithForm - */ - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /pet/{petId}/uploadImage : uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return successful operation (status code 200) - * @see PetApi#uploadFile - */ - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java index 0128cb2d54b8..831650ae3d69 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java @@ -8,20 +8,28 @@ import java.util.Map; import org.openapitools.model.Order; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "the store API") public interface StoreApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * DELETE /store/order/{order_id} : Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -37,7 +45,10 @@ public interface StoreApi { @DeleteMapping( value = "/store/order/{order_id}" ) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); + default ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -55,7 +66,10 @@ public interface StoreApi { value = "/store/inventory", produces = { "application/json" } ) - ResponseEntity> getInventory(); + default ResponseEntity> getInventory() { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -76,7 +90,24 @@ public interface StoreApi { value = "/store/order/{order_id}", produces = { "application/xml", "application/json" } ) - ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); + default ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -94,6 +125,23 @@ public interface StoreApi { value = "/store/order", produces = { "application/xml", "application/json" } ) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); + default ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java index 1a02c0b756d1..1293b5c8f6e4 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApiController.java @@ -1,26 +1,9 @@ package org.openapitools.api; -import java.util.Map; -import org.openapitools.model.Order; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -33,82 +16,9 @@ public StoreApiController(NativeWebRequest request) { this.request = request; } - /** - * DELETE /store/order/{order_id} : Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @param orderId ID of the order that needs to be deleted (required) - * @return Invalid ID supplied (status code 400) - * or Order not found (status code 404) - * @see StoreApi#deleteOrder - */ - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /store/inventory : Returns pet inventories by status - * Returns a map of status codes to quantities - * - * @return successful operation (status code 200) - * @see StoreApi#getInventory - */ - public ResponseEntity> getInventory() { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /store/order/{order_id} : Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @param orderId ID of pet that needs to be fetched (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Order not found (status code 404) - * @see StoreApi#getOrderById - */ - public ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /store/order : Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return successful operation (status code 200) - * or Invalid Order (status code 400) - * @see StoreApi#placeOrder - */ - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java index e1d4245a6b15..f6b591946bc3 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java @@ -8,20 +8,28 @@ import java.util.List; import org.openapitools.model.User; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "the user API") public interface UserApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /user : Create user * This can only be done by the logged in user. @@ -35,7 +43,10 @@ public interface UserApi { @PostMapping( value = "/user" ) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -50,7 +61,10 @@ public interface UserApi { @PostMapping( value = "/user/createWithArray" ) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); + default ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -65,7 +79,10 @@ public interface UserApi { @PostMapping( value = "/user/createWithList" ) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); + default ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -83,7 +100,10 @@ public interface UserApi { @DeleteMapping( value = "/user/{username}" ) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); + default ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -103,7 +123,24 @@ public interface UserApi { value = "/user/{username}", produces = { "application/xml", "application/json" } ) - ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username); + default ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123 "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -122,7 +159,10 @@ public interface UserApi { value = "/user/login", produces = { "application/xml", "application/json" } ) - ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); + default ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -136,7 +176,10 @@ public interface UserApi { @GetMapping( value = "/user/logout" ) - ResponseEntity logoutUser(); + default ResponseEntity logoutUser() { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -155,6 +198,9 @@ public interface UserApi { @PutMapping( value = "/user/{username}" ) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java index 3950bf5f863d..3f6c4d9a2d6f 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApiController.java @@ -1,26 +1,9 @@ package org.openapitools.api; -import java.util.List; -import org.openapitools.model.User; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -33,121 +16,9 @@ public UserApiController(NativeWebRequest request) { this.request = request; } - /** - * POST /user : Create user - * This can only be done by the logged in user. - * - * @param body Created user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUser - */ - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /user/createWithArray : Creates list of users with given input array - * - * @param body List of user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUsersWithArrayInput - */ - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /user/createWithList : Creates list of users with given input array - * - * @param body List of user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUsersWithListInput - */ - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * DELETE /user/{username} : Delete user - * This can only be done by the logged in user. - * - * @param username The name that needs to be deleted (required) - * @return Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#deleteUser - */ - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /user/{username} : Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return successful operation (status code 200) - * or Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#getUserByName - */ - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123 "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /user/login : Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return successful operation (status code 200) - * or Invalid username/password supplied (status code 400) - * @see UserApi#loginUser - */ - public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /user/logout : Logs out current logged in user session - * - * @return successful operation (status code 200) - * @see UserApi#logoutUser - */ - public ResponseEntity logoutUser() { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /user/{username} : Updated user - * This can only be done by the logged in user. - * - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return Invalid user supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#updateUser - */ - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java deleted file mode 100644 index 8f936b311447..000000000000 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java +++ /dev/null @@ -1,232 +0,0 @@ -package org.openapitools.configuration; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonTokenId; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; -import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; -import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; -import com.fasterxml.jackson.datatype.threetenbp.function.Function; -import org.threeten.bp.DateTimeException; -import org.threeten.bp.DateTimeUtils; -import org.threeten.bp.Instant; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZoneId; -import org.threeten.bp.ZonedDateTime; -import org.threeten.bp.format.DateTimeFormatter; -import org.threeten.bp.temporal.Temporal; -import org.threeten.bp.temporal.TemporalAccessor; - -import java.io.IOException; -import java.math.BigDecimal; - -/** - * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. - * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. - * - * @author Nick Williams - */ -public class CustomInstantDeserializer - extends ThreeTenDateTimeDeserializerBase { - private static final long serialVersionUID = 1L; - - public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( - Instant.class, DateTimeFormatter.ISO_INSTANT, - new Function() { - @Override - public Instant apply(TemporalAccessor temporalAccessor) { - return Instant.from(temporalAccessor); - } - }, - new Function() { - @Override - public Instant apply(FromIntegerArguments a) { - return Instant.ofEpochMilli(a.value); - } - }, - new Function() { - @Override - public Instant apply(FromDecimalArguments a) { - return Instant.ofEpochSecond(a.integer, a.fraction); - } - }, - null - ); - - public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( - OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, - new Function() { - @Override - public OffsetDateTime apply(TemporalAccessor temporalAccessor) { - return OffsetDateTime.from(temporalAccessor); - } - }, - new Function() { - @Override - public OffsetDateTime apply(FromIntegerArguments a) { - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); - } - }, - new Function() { - @Override - public OffsetDateTime apply(FromDecimalArguments a) { - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); - } - }, - new BiFunction() { - @Override - public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { - return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); - } - } - ); - - public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( - ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, - new Function() { - @Override - public ZonedDateTime apply(TemporalAccessor temporalAccessor) { - return ZonedDateTime.from(temporalAccessor); - } - }, - new Function() { - @Override - public ZonedDateTime apply(FromIntegerArguments a) { - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); - } - }, - new Function() { - @Override - public ZonedDateTime apply(FromDecimalArguments a) { - return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); - } - }, - new BiFunction() { - @Override - public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { - return zonedDateTime.withZoneSameInstant(zoneId); - } - } - ); - - protected final Function fromMilliseconds; - - protected final Function fromNanoseconds; - - protected final Function parsedToValue; - - protected final BiFunction adjust; - - protected CustomInstantDeserializer(Class supportedType, - DateTimeFormatter parser, - Function parsedToValue, - Function fromMilliseconds, - Function fromNanoseconds, - BiFunction adjust) { - super(supportedType, parser); - this.parsedToValue = parsedToValue; - this.fromMilliseconds = fromMilliseconds; - this.fromNanoseconds = fromNanoseconds; - this.adjust = adjust == null ? new BiFunction() { - @Override - public T apply(T t, ZoneId zoneId) { - return t; - } - } : adjust; - } - - @SuppressWarnings("unchecked") - protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { - super((Class) base.handledType(), f); - parsedToValue = base.parsedToValue; - fromMilliseconds = base.fromMilliseconds; - fromNanoseconds = base.fromNanoseconds; - adjust = base.adjust; - } - - @Override - protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { - if (dtf == _formatter) { - return this; - } - return new CustomInstantDeserializer(this, dtf); - } - - @Override - public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { - //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only - //string values have to be adjusted to the configured TZ. - switch (parser.getCurrentTokenId()) { - case JsonTokenId.ID_NUMBER_FLOAT: { - BigDecimal value = parser.getDecimalValue(); - long seconds = value.longValue(); - int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); - return fromNanoseconds.apply(new FromDecimalArguments( - seconds, nanoseconds, getZone(context))); - } - - case JsonTokenId.ID_NUMBER_INT: { - long timestamp = parser.getLongValue(); - if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { - return this.fromNanoseconds.apply(new FromDecimalArguments( - timestamp, 0, this.getZone(context) - )); - } - return this.fromMilliseconds.apply(new FromIntegerArguments( - timestamp, this.getZone(context) - )); - } - - case JsonTokenId.ID_STRING: { - String string = parser.getText().trim(); - if (string.length() == 0) { - return null; - } - if (string.endsWith("+0000")) { - string = string.substring(0, string.length() - 5) + "Z"; - } - T value; - try { - TemporalAccessor acc = _formatter.parse(string); - value = parsedToValue.apply(acc); - if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { - return adjust.apply(value, this.getZone(context)); - } - } catch (DateTimeException e) { - throw _peelDTE(e); - } - return value; - } - } - throw context.mappingException("Expected type float, integer, or string."); - } - - private ZoneId getZone(DeserializationContext context) { - // Instants are always in UTC, so don't waste compute cycles - return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); - } - - private static class FromIntegerArguments { - public final long value; - public final ZoneId zoneId; - - private FromIntegerArguments(long value, ZoneId zoneId) { - this.value = value; - this.zoneId = zoneId; - } - } - - private static class FromDecimalArguments { - public final long integer; - public final int fraction; - public final ZoneId zoneId; - - private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { - this.integer = integer; - this.fraction = fraction; - this.zoneId = zoneId; - } - } -} diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/JacksonConfiguration.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/JacksonConfiguration.java deleted file mode 100644 index b481a87518f4..000000000000 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/JacksonConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openapitools.configuration; - -import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.threeten.bp.Instant; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZonedDateTime; - -@Configuration -public class JacksonConfiguration { - - @Bean - @ConditionalOnMissingBean(ThreeTenModule.class) - ThreeTenModule threeTenModule() { - ThreeTenModule module = new ThreeTenModule(); - module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); - module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); - module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); - return module; - } -} diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java index 425e530b93b1..589dd7dc5e7f 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java @@ -40,8 +40,9 @@ public Docket customImplementation(ServletContext servletContext, @Value("${open .select() .apis(RequestHandlerSelectors.basePackage("org.openapitools.api")) .build() - .directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class) - .directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class) + .pathProvider(new BasePathAwareRelativePathProvider(servletContext, basePath)) + .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java index 1e2c8c2726d3..76a9f4e4c256 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -66,7 +66,7 @@ public AdditionalPropertiesClass mapString(Map mapString) { public AdditionalPropertiesClass putMapStringItem(String key, String mapStringItem) { if (this.mapString == null) { - this.mapString = new HashMap(); + this.mapString = new HashMap<>(); } this.mapString.put(key, mapStringItem); return this; @@ -94,7 +94,7 @@ public AdditionalPropertiesClass mapNumber(Map mapNumber) { public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumberItem) { if (this.mapNumber == null) { - this.mapNumber = new HashMap(); + this.mapNumber = new HashMap<>(); } this.mapNumber.put(key, mapNumberItem); return this; @@ -123,7 +123,7 @@ public AdditionalPropertiesClass mapInteger(Map mapInteger) { public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntegerItem) { if (this.mapInteger == null) { - this.mapInteger = new HashMap(); + this.mapInteger = new HashMap<>(); } this.mapInteger.put(key, mapIntegerItem); return this; @@ -151,7 +151,7 @@ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBooleanItem) { if (this.mapBoolean == null) { - this.mapBoolean = new HashMap(); + this.mapBoolean = new HashMap<>(); } this.mapBoolean.put(key, mapBooleanItem); return this; @@ -179,7 +179,7 @@ public AdditionalPropertiesClass mapArrayInteger(Map> mapA public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List mapArrayIntegerItem) { if (this.mapArrayInteger == null) { - this.mapArrayInteger = new HashMap>(); + this.mapArrayInteger = new HashMap<>(); } this.mapArrayInteger.put(key, mapArrayIntegerItem); return this; @@ -208,7 +208,7 @@ public AdditionalPropertiesClass mapArrayAnytype(Map> mapAr public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List mapArrayAnytypeItem) { if (this.mapArrayAnytype == null) { - this.mapArrayAnytype = new HashMap>(); + this.mapArrayAnytype = new HashMap<>(); } this.mapArrayAnytype.put(key, mapArrayAnytypeItem); return this; @@ -237,7 +237,7 @@ public AdditionalPropertiesClass mapMapString(Map> m public AdditionalPropertiesClass putMapMapStringItem(String key, Map mapMapStringItem) { if (this.mapMapString == null) { - this.mapMapString = new HashMap>(); + this.mapMapString = new HashMap<>(); } this.mapMapString.put(key, mapMapStringItem); return this; @@ -266,7 +266,7 @@ public AdditionalPropertiesClass mapMapAnytype(Map> public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map mapMapAnytypeItem) { if (this.mapMapAnytype == null) { - this.mapMapAnytype = new HashMap>(); + this.mapMapAnytype = new HashMap<>(); } this.mapMapAnytype.put(key, mapMapAnytypeItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 9c226efbbc46..aec96b23f033 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -28,7 +28,7 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList>(); + this.arrayArrayNumber = new ArrayList<>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java index 51ea58aab386..63a657c8dddf 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -28,7 +28,7 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList(); + this.arrayNumber = new ArrayList<>(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java index 1fea247ab3ca..2a36629dfc75 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java @@ -36,7 +36,7 @@ public ArrayTest arrayOfString(List arrayOfString) { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList(); + this.arrayOfString = new ArrayList<>(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -64,7 +64,7 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList>(); + this.arrayArrayOfInteger = new ArrayList<>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -93,7 +93,7 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList>(); + this.arrayArrayOfModel = new ArrayList<>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/EnumArrays.java index 90d7bf130bb1..ec2d4e1ce8b9 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/EnumArrays.java @@ -121,7 +121,7 @@ public EnumArrays arrayEnum(List arrayEnum) { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList(); + this.arrayEnum = new ArrayList<>(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FileSchemaTestClass.java index a99196c28084..8e4f8d5d5d9d 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FileSchemaTestClass.java @@ -51,7 +51,7 @@ public FileSchemaTestClass files(List files) { public FileSchemaTestClass addFilesItem(java.io.File filesItem) { if (this.files == null) { - this.files = new ArrayList(); + this.files = new ArrayList<>(); } this.files.add(filesItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java index 533569e421dc..55298e86211e 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java @@ -6,10 +6,10 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; import java.util.UUID; import org.springframework.core.io.Resource; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MapTest.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MapTest.java index b1d48c044ada..7b9a321ecb22 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MapTest.java @@ -76,7 +76,7 @@ public MapTest mapMapOfString(Map> mapMapOfString) { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap>(); + this.mapMapOfString = new HashMap<>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -105,7 +105,7 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap(); + this.mapOfEnumString = new HashMap<>(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; @@ -133,7 +133,7 @@ public MapTest directMap(Map directMap) { public MapTest putDirectMapItem(String key, Boolean directMapItem) { if (this.directMap == null) { - this.directMap = new HashMap(); + this.directMap = new HashMap<>(); } this.directMap.put(key, directMapItem); return this; @@ -161,7 +161,7 @@ public MapTest indirectMap(Map indirectMap) { public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { if (this.indirectMap == null) { - this.indirectMap = new HashMap(); + this.indirectMap = new HashMap<>(); } this.indirectMap.put(key, indirectMapItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 71693227fa7a..d80573256c63 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -5,12 +5,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.openapitools.model.Animal; -import org.threeten.bp.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; @@ -80,7 +80,7 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.map.put(key, mapItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Order.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Order.java index 06a8fdb89353..0c9dddf85daf 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Order.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Pet.java index 5f8b54eb5734..5f44cab5669e 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/Pet.java @@ -32,7 +32,7 @@ public class Pet { @JsonProperty("photoUrls") @Valid - private Set photoUrls = new LinkedHashSet(); + private Set photoUrls = new LinkedHashSet<>(); @JsonProperty("tags") @Valid @@ -173,7 +173,7 @@ public Pet tags(List tags) { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList(); + this.tags = new ArrayList<>(); } this.tags.add(tagsItem); return this; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderDefault.java index bcf00b393fd4..80788f31612a 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderDefault.java @@ -31,7 +31,7 @@ public class TypeHolderDefault { @JsonProperty("array_item") @Valid - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderDefault stringItem(String stringItem) { this.stringItem = stringItem; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderExample.java index 2151f844f8ed..963c3c66b57b 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/TypeHolderExample.java @@ -34,7 +34,7 @@ public class TypeHolderExample { @JsonProperty("array_item") @Valid - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderExample stringItem(String stringItem) { this.stringItem = stringItem; diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/XmlItem.java index 9240d5345a67..465b94b6a88d 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/XmlItem.java @@ -201,7 +201,7 @@ public XmlItem wrappedArray(List wrappedArray) { public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { if (this.wrappedArray == null) { - this.wrappedArray = new ArrayList(); + this.wrappedArray = new ArrayList<>(); } this.wrappedArray.add(wrappedArrayItem); return this; @@ -310,7 +310,7 @@ public XmlItem nameArray(List nameArray) { public XmlItem addNameArrayItem(Integer nameArrayItem) { if (this.nameArray == null) { - this.nameArray = new ArrayList(); + this.nameArray = new ArrayList<>(); } this.nameArray.add(nameArrayItem); return this; @@ -338,7 +338,7 @@ public XmlItem nameWrappedArray(List nameWrappedArray) { public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { if (this.nameWrappedArray == null) { - this.nameWrappedArray = new ArrayList(); + this.nameWrappedArray = new ArrayList<>(); } this.nameWrappedArray.add(nameWrappedArrayItem); return this; @@ -447,7 +447,7 @@ public XmlItem prefixArray(List prefixArray) { public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { if (this.prefixArray == null) { - this.prefixArray = new ArrayList(); + this.prefixArray = new ArrayList<>(); } this.prefixArray.add(prefixArrayItem); return this; @@ -475,7 +475,7 @@ public XmlItem prefixWrappedArray(List prefixWrappedArray) { public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { if (this.prefixWrappedArray == null) { - this.prefixWrappedArray = new ArrayList(); + this.prefixWrappedArray = new ArrayList<>(); } this.prefixWrappedArray.add(prefixWrappedArrayItem); return this; @@ -584,7 +584,7 @@ public XmlItem namespaceArray(List namespaceArray) { public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { if (this.namespaceArray == null) { - this.namespaceArray = new ArrayList(); + this.namespaceArray = new ArrayList<>(); } this.namespaceArray.add(namespaceArrayItem); return this; @@ -612,7 +612,7 @@ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { if (this.namespaceWrappedArray == null) { - this.namespaceWrappedArray = new ArrayList(); + this.namespaceWrappedArray = new ArrayList<>(); } this.namespaceWrappedArray.add(namespaceWrappedArrayItem); return this; @@ -721,7 +721,7 @@ public XmlItem prefixNsArray(List prefixNsArray) { public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { if (this.prefixNsArray == null) { - this.prefixNsArray = new ArrayList(); + this.prefixNsArray = new ArrayList<>(); } this.prefixNsArray.add(prefixNsArrayItem); return this; @@ -749,7 +749,7 @@ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { if (this.prefixNsWrappedArray == null) { - this.prefixNsWrappedArray = new ArrayList(); + this.prefixNsWrappedArray = new ArrayList<>(); } this.prefixNsWrappedArray.add(prefixNsWrappedArrayItem); return this; diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/RFC3339DateFormat.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/RFC3339DateFormat.java index 026bb3168c62..bcd3936d8b34 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/RFC3339DateFormat.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/RFC3339DateFormat.java @@ -1,22 +1,38 @@ package org.openapitools; -import com.fasterxml.jackson.databind.util.ISO8601DateFormat; -import com.fasterxml.jackson.databind.util.ISO8601Utils; +import com.fasterxml.jackson.databind.util.StdDateFormat; +import java.text.DateFormat; import java.text.FieldPosition; +import java.text.ParsePosition; import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); -public class RFC3339DateFormat extends ISO8601DateFormat { + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); - private static final long serialVersionUID = 1L; + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } - // Same as ISO8601DateFormat but serializing milliseconds. @Override public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { - String value = ISO8601Utils.format(date, true); - toAppendTo.append(value); - return toAppendTo; + return fmt.format(date, toAppendTo, fieldPosition); } + @Override + public Object clone() { + return this; + } } \ No newline at end of file From 08fe44c764bec7904de7eead928ffd67916876dc Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Fri, 28 Aug 2020 09:44:55 +0800 Subject: [PATCH 06/11] [C][Client][Clang Static Analyzer] Fix uninitialized argument value (#7305) --- .../resources/C-libcurl/api-body.mustache | 104 +++++++++++++----- samples/client/petstore/c/api/PetAPI.c | 49 ++++++--- samples/client/petstore/c/api/StoreAPI.c | 7 +- samples/client/petstore/c/api/UserAPI.c | 56 +++++++--- 4 files changed, 159 insertions(+), 57 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache index 3752fcfce1e1..a80a14d812e5 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache @@ -193,7 +193,7 @@ end: {{#headerParams}} // header parameters - char *keyHeader_{{{paramName}}}; + char *keyHeader_{{{paramName}}} = NULL; {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueHeader_{{{paramName}}}; keyValuePair_t *keyPairHeader_{{paramName}} = 0; if ({{paramName}}) { @@ -242,12 +242,12 @@ end: // form parameters {{#isFile}} - char *keyForm_{{paramName}}; + char *keyForm_{{paramName}} = NULL; {{{dataType}}} valueForm_{{paramName}}; keyValuePair_t *keyPairForm_{{paramName}} = 0; {{/isFile}} {{^isFile}} - char *keyForm_{{paramName}}; + char *keyForm_{{paramName}} = NULL; {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}}{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueForm_{{paramName}}; keyValuePair_t *keyPairForm_{{paramName}} = 0; {{/isFile}} @@ -272,9 +272,9 @@ end: // Body Param {{#isListContainer}} //notstring - cJSON *localVar_{{paramName}}; - cJSON *localVarItemJSON_{{paramName}}; - cJSON *localVarSingleItemJSON_{{paramName}}; + cJSON *localVar_{{paramName}} = NULL; + cJSON *localVarItemJSON_{{paramName}} = NULL; + cJSON *localVarSingleItemJSON_{{paramName}} = NULL; if ({{paramName}} != NULL) { localVarItemJSON_{{paramName}} = cJSON_CreateObject(); @@ -300,7 +300,7 @@ end: } {{/isListContainer}} {{^isListContainer}} - cJSON *localVarSingleItemJSON_{{paramName}}; + cJSON *localVarSingleItemJSON_{{paramName}} = NULL; if ({{paramName}} != NULL) { //string @@ -399,23 +399,41 @@ end: {{/pathParams}} {{#headerParams}} {{#isString}} - free(keyHeader_{{{paramName}}}); + if (keyHeader_{{{paramName}}}) { + free(keyHeader_{{{paramName}}}); + keyHeader_{{{paramName}}} = NULL; + } free(valueHeader_{{{paramName}}}); {{/isString}} {{^isString}} - free(keyHeader_{{{paramName}}}); + if (keyHeader_{{{paramName}}}) { + free(keyHeader_{{{paramName}}}); + keyHeader_{{{paramName}}} = NULL; + } {{/isString}} free(keyPairHeader_{{paramName}}); {{/headerParams}} {{#bodyParams}} {{#isListContainer}} - cJSON_Delete(localVarItemJSON_{{paramName}}); - cJSON_Delete(localVarSingleItemJSON_{{paramName}}); - cJSON_Delete(localVar_{{paramName}}); + if (localVarItemJSON_{{paramName}}) { + cJSON_Delete(localVarItemJSON_{{paramName}}); + localVarItemJSON_{{paramName}} = NULL; + } + if (localVarSingleItemJSON_{{paramName}}) { + cJSON_Delete(localVarSingleItemJSON_{{paramName}}); + localVarSingleItemJSON_{{paramName}} = NULL; + } + if (localVar_{{paramName}}) { + cJSON_Delete(localVar_{{paramName}}); + localVar_{{paramName}} = NULL; + } free(localVarBodyParameters); {{/isListContainer}} {{^isListContainer}} - cJSON_Delete(localVarSingleItemJSON_{{paramName}}); + if (localVarSingleItemJSON_{{paramName}}) { + cJSON_Delete(localVarSingleItemJSON_{{paramName}}); + localVarSingleItemJSON_{{paramName}} = NULL; + } free(localVarBodyParameters); {{/isListContainer}} {{/bodyParams}} @@ -451,19 +469,28 @@ end: {{/queryParams}} {{#formParams}} {{#isFile}} - free(keyForm_{{{paramName}}}); + if (keyForm_{{{paramName}}}) { + free(keyForm_{{{paramName}}}); + keyForm_{{{paramName}}} = NULL; + } // free(fileVar_{{paramName}}->data); // free(fileVar_{{paramName}}); free(keyPairForm_{{paramName}}); {{/isFile}} {{^isFile}} {{#isString}} - free(keyForm_{{{paramName}}}); + if (keyForm_{{{paramName}}}) { + free(keyForm_{{{paramName}}}); + keyForm_{{{paramName}}} = NULL; + } free(valueForm_{{{paramName}}}); free(keyPairForm_{{paramName}}); {{/isString}} {{^isString}} - free(keyForm_{{{paramName}}}); + if (keyForm_{{{paramName}}}) { + free(keyForm_{{{paramName}}}); + keyForm_{{{paramName}}} = NULL; + } free(keyPairForm_{{paramName}}); {{/isString}} {{/isFile}} @@ -492,23 +519,41 @@ end: {{/pathParams}} {{#headerParams}} {{#isString}} - free(keyHeader_{{{paramName}}}); + if (keyHeader_{{{paramName}}}) { + free(keyHeader_{{{paramName}}}); + keyHeader_{{{paramName}}} = NULL; + } free(valueHeader_{{{paramName}}}); {{/isString}} {{^isString}} - free(keyHeader_{{{paramName}}}); + if (keyHeader_{{{paramName}}}) { + free(keyHeader_{{{paramName}}}); + keyHeader_{{{paramName}}} = NULL; + } {{/isString}} free(keyPairHeader_{{paramName}}); {{/headerParams}} {{#bodyParams}} {{#isListContainer}} - cJSON_Delete(localVarItemJSON_{{paramName}}); - cJSON_Delete(localVarSingleItemJSON_{{paramName}}); - cJSON_Delete(localVar_{{paramName}}); + if (localVarItemJSON_{{paramName}}) { + cJSON_Delete(localVarItemJSON_{{paramName}}); + localVarItemJSON_{{paramName}} = NULL; + } + if (localVarSingleItemJSON_{{paramName}}) { + cJSON_Delete(localVarSingleItemJSON_{{paramName}}); + localVarSingleItemJSON_{{paramName}} = NULL; + } + if (localVar_{{paramName}}) { + cJSON_Delete(localVar_{{paramName}}); + localVar_{{paramName}} = NULL; + } free(localVarBodyParameters); {{/isListContainer}} {{^isListContainer}} - cJSON_Delete(localVarSingleItemJSON_{{paramName}}); + if (localVarSingleItemJSON_{{paramName}}) { + cJSON_Delete(localVarSingleItemJSON_{{paramName}}); + localVarSingleItemJSON_{{paramName}} = NULL; + } free(localVarBodyParameters); {{/isListContainer}} {{/bodyParams}} @@ -542,18 +587,27 @@ end: {{/queryParams}} {{#formParams}} {{#isFile}} - free(keyForm_{{{paramName}}}); + if (keyForm_{{{paramName}}}) { + free(keyForm_{{{paramName}}}); + keyForm_{{{paramName}}} = NULL; + } // free(fileVar_{{paramName}}->data); // free(fileVar_{{paramName}}); {{/isFile}} {{^isFile}} {{#isString}} - free(keyForm_{{{paramName}}}); + if (keyForm_{{{paramName}}}) { + free(keyForm_{{{paramName}}}); + keyForm_{{{paramName}}} = NULL; + } free(valueForm_{{{paramName}}}); keyValuePair_free(keyPairForm_{{{paramName}}}); {{/isString}} {{^isString}} - free(keyForm_{{{paramName}}}); + if (keyForm_{{{paramName}}}) { + free(keyForm_{{{paramName}}}); + keyForm_{{{paramName}}} = NULL; + } free(keyPairForm_{{paramName}}); {{/isString}} {{/isFile}} diff --git a/samples/client/petstore/c/api/PetAPI.c b/samples/client/petstore/c/api/PetAPI.c index aa3db38496a3..75043dcf9a1a 100644 --- a/samples/client/petstore/c/api/PetAPI.c +++ b/samples/client/petstore/c/api/PetAPI.c @@ -76,7 +76,7 @@ PetAPI_addPet(apiClient_t *apiClient, pet_t * body ) // Body Param - cJSON *localVarSingleItemJSON_body; + cJSON *localVarSingleItemJSON_body = NULL; if (body != NULL) { //string @@ -111,7 +111,10 @@ PetAPI_addPet(apiClient_t *apiClient, pet_t * body ) list_free(localVarContentType); free(localVarPath); - cJSON_Delete(localVarSingleItemJSON_body); + if (localVarSingleItemJSON_body) { + cJSON_Delete(localVarSingleItemJSON_body); + localVarSingleItemJSON_body = NULL; + } free(localVarBodyParameters); } @@ -151,7 +154,7 @@ PetAPI_deletePet(apiClient_t *apiClient, long petId , char * api_key ) // header parameters - char *keyHeader_api_key; + char *keyHeader_api_key = NULL; char * valueHeader_api_key; keyValuePair_t *keyPairHeader_api_key = 0; if (api_key) { @@ -188,7 +191,10 @@ PetAPI_deletePet(apiClient_t *apiClient, long petId , char * api_key ) free(localVarPath); free(localVarToReplace_petId); - free(keyHeader_api_key); + if (keyHeader_api_key) { + free(keyHeader_api_key); + keyHeader_api_key = NULL; + } free(valueHeader_api_key); free(keyPairHeader_api_key); @@ -463,7 +469,7 @@ PetAPI_updatePet(apiClient_t *apiClient, pet_t * body ) // Body Param - cJSON *localVarSingleItemJSON_body; + cJSON *localVarSingleItemJSON_body = NULL; if (body != NULL) { //string @@ -504,7 +510,10 @@ PetAPI_updatePet(apiClient_t *apiClient, pet_t * body ) list_free(localVarContentType); free(localVarPath); - cJSON_Delete(localVarSingleItemJSON_body); + if (localVarSingleItemJSON_body) { + cJSON_Delete(localVarSingleItemJSON_body); + localVarSingleItemJSON_body = NULL; + } free(localVarBodyParameters); } @@ -544,7 +553,7 @@ PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId , char * name , char // form parameters - char *keyForm_name; + char *keyForm_name = NULL; char * valueForm_name; keyValuePair_t *keyPairForm_name = 0; if (name != NULL) @@ -556,7 +565,7 @@ PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId , char * name , char } // form parameters - char *keyForm_status; + char *keyForm_status = NULL; char * valueForm_status; keyValuePair_t *keyPairForm_status = 0; if (status != NULL) @@ -594,10 +603,16 @@ PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId , char * name , char list_free(localVarContentType); free(localVarPath); free(localVarToReplace_petId); - free(keyForm_name); + if (keyForm_name) { + free(keyForm_name); + keyForm_name = NULL; + } free(valueForm_name); keyValuePair_free(keyPairForm_name); - free(keyForm_status); + if (keyForm_status) { + free(keyForm_status); + keyForm_status = NULL; + } free(valueForm_status); keyValuePair_free(keyPairForm_status); @@ -638,7 +653,7 @@ PetAPI_uploadFile(apiClient_t *apiClient, long petId , char * additionalMetadata // form parameters - char *keyForm_additionalMetadata; + char *keyForm_additionalMetadata = NULL; char * valueForm_additionalMetadata; keyValuePair_t *keyPairForm_additionalMetadata = 0; if (additionalMetadata != NULL) @@ -650,7 +665,7 @@ PetAPI_uploadFile(apiClient_t *apiClient, long petId , char * additionalMetadata } // form parameters - char *keyForm_file; + char *keyForm_file = NULL; binary_t* valueForm_file; keyValuePair_t *keyPairForm_file = 0; if (file != NULL) @@ -696,10 +711,16 @@ PetAPI_uploadFile(apiClient_t *apiClient, long petId , char * additionalMetadata list_free(localVarContentType); free(localVarPath); free(localVarToReplace_petId); - free(keyForm_additionalMetadata); + if (keyForm_additionalMetadata) { + free(keyForm_additionalMetadata); + keyForm_additionalMetadata = NULL; + } free(valueForm_additionalMetadata); free(keyPairForm_additionalMetadata); - free(keyForm_file); + if (keyForm_file) { + free(keyForm_file); + keyForm_file = NULL; + } // free(fileVar_file->data); // free(fileVar_file); free(keyPairForm_file); diff --git a/samples/client/petstore/c/api/StoreAPI.c b/samples/client/petstore/c/api/StoreAPI.c index 9d8a539c304c..773dfbbd9cd2 100644 --- a/samples/client/petstore/c/api/StoreAPI.c +++ b/samples/client/petstore/c/api/StoreAPI.c @@ -244,7 +244,7 @@ StoreAPI_placeOrder(apiClient_t *apiClient, order_t * body ) // Body Param - cJSON *localVarSingleItemJSON_body; + cJSON *localVarSingleItemJSON_body = NULL; if (body != NULL) { //string @@ -289,7 +289,10 @@ StoreAPI_placeOrder(apiClient_t *apiClient, order_t * body ) list_free(localVarHeaderType); free(localVarPath); - cJSON_Delete(localVarSingleItemJSON_body); + if (localVarSingleItemJSON_body) { + cJSON_Delete(localVarSingleItemJSON_body); + localVarSingleItemJSON_body = NULL; + } free(localVarBodyParameters); return elementToReturn; end: diff --git a/samples/client/petstore/c/api/UserAPI.c b/samples/client/petstore/c/api/UserAPI.c index 5fdba8bc2a72..22f4a5214e16 100644 --- a/samples/client/petstore/c/api/UserAPI.c +++ b/samples/client/petstore/c/api/UserAPI.c @@ -35,7 +35,7 @@ UserAPI_createUser(apiClient_t *apiClient, user_t * body ) // Body Param - cJSON *localVarSingleItemJSON_body; + cJSON *localVarSingleItemJSON_body = NULL; if (body != NULL) { //string @@ -68,7 +68,10 @@ UserAPI_createUser(apiClient_t *apiClient, user_t * body ) free(localVarPath); - cJSON_Delete(localVarSingleItemJSON_body); + if (localVarSingleItemJSON_body) { + cJSON_Delete(localVarSingleItemJSON_body); + localVarSingleItemJSON_body = NULL; + } free(localVarBodyParameters); } @@ -95,9 +98,9 @@ UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t * body ) // Body Param //notstring - cJSON *localVar_body; - cJSON *localVarItemJSON_body; - cJSON *localVarSingleItemJSON_body; + cJSON *localVar_body = NULL; + cJSON *localVarItemJSON_body = NULL; + cJSON *localVarSingleItemJSON_body = NULL; if (body != NULL) { localVarItemJSON_body = cJSON_CreateObject(); @@ -147,9 +150,18 @@ UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t * body ) free(localVarPath); - cJSON_Delete(localVarItemJSON_body); - cJSON_Delete(localVarSingleItemJSON_body); - cJSON_Delete(localVar_body); + if (localVarItemJSON_body) { + cJSON_Delete(localVarItemJSON_body); + localVarItemJSON_body = NULL; + } + if (localVarSingleItemJSON_body) { + cJSON_Delete(localVarSingleItemJSON_body); + localVarSingleItemJSON_body = NULL; + } + if (localVar_body) { + cJSON_Delete(localVar_body); + localVar_body = NULL; + } free(localVarBodyParameters); } @@ -176,9 +188,9 @@ UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t * body ) // Body Param //notstring - cJSON *localVar_body; - cJSON *localVarItemJSON_body; - cJSON *localVarSingleItemJSON_body; + cJSON *localVar_body = NULL; + cJSON *localVarItemJSON_body = NULL; + cJSON *localVarSingleItemJSON_body = NULL; if (body != NULL) { localVarItemJSON_body = cJSON_CreateObject(); @@ -228,9 +240,18 @@ UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t * body ) free(localVarPath); - cJSON_Delete(localVarItemJSON_body); - cJSON_Delete(localVarSingleItemJSON_body); - cJSON_Delete(localVar_body); + if (localVarItemJSON_body) { + cJSON_Delete(localVarItemJSON_body); + localVarItemJSON_body = NULL; + } + if (localVarSingleItemJSON_body) { + cJSON_Delete(localVarSingleItemJSON_body); + localVarSingleItemJSON_body = NULL; + } + if (localVar_body) { + cJSON_Delete(localVar_body); + localVar_body = NULL; + } free(localVarBodyParameters); } @@ -564,7 +585,7 @@ UserAPI_updateUser(apiClient_t *apiClient, char * username , user_t * body ) // Body Param - cJSON *localVarSingleItemJSON_body; + cJSON *localVarSingleItemJSON_body = NULL; if (body != NULL) { //string @@ -601,7 +622,10 @@ UserAPI_updateUser(apiClient_t *apiClient, char * username , user_t * body ) free(localVarPath); free(localVarToReplace_username); - cJSON_Delete(localVarSingleItemJSON_body); + if (localVarSingleItemJSON_body) { + cJSON_Delete(localVarSingleItemJSON_body); + localVarSingleItemJSON_body = NULL; + } free(localVarBodyParameters); } From 1f95199f822e6adb23c1920ff5b67d5879a7a9e0 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Fri, 28 Aug 2020 19:17:20 +0800 Subject: [PATCH 07/11] update spring config to use java8 (#7308) --- bin/configs/spring-boot-delegate.yaml | 2 +- bin/configs/spring-mvc.yaml | 2 +- .../spring-mvc/.openapi-generator/FILES | 1 - samples/server/petstore/spring-mvc/pom.xml | 8 +- .../org/openapitools/api/AnotherFakeApi.java | 22 +- .../api/AnotherFakeApiController.java | 39 +-- .../java/org/openapitools/api/FakeApi.java | 118 ++++++-- .../openapitools/api/FakeApiController.java | 276 +----------------- .../api/FakeClassnameTestApi.java | 22 +- .../api/FakeClassnameTestApiController.java | 39 +-- .../java/org/openapitools/api/PetApi.java | 99 ++++++- .../openapitools/api/PetApiController.java | 179 +----------- .../java/org/openapitools/api/StoreApi.java | 56 +++- .../openapitools/api/StoreApiController.java | 98 +------ .../java/org/openapitools/api/UserApi.java | 62 +++- .../openapitools/api/UserApiController.java | 137 +-------- .../CustomInstantDeserializer.java | 232 --------------- .../OpenAPIDocumentationConfig.java | 5 +- .../configuration/OpenAPIUiConfiguration.java | 10 +- .../model/AdditionalPropertiesClass.java | 16 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../openapitools/model/ArrayOfNumberOnly.java | 2 +- .../org/openapitools/model/ArrayTest.java | 6 +- .../org/openapitools/model/EnumArrays.java | 2 +- .../model/FileSchemaTestClass.java | 2 +- .../org/openapitools/model/FormatTest.java | 4 +- .../java/org/openapitools/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 4 +- .../java/org/openapitools/model/Order.java | 2 +- .../main/java/org/openapitools/model/Pet.java | 4 +- .../openapitools/model/TypeHolderDefault.java | 2 +- .../openapitools/model/TypeHolderExample.java | 2 +- .../java/org/openapitools/model/XmlItem.java | 18 +- .../.openapi-generator/FILES | 2 - .../petstore/springboot-delegate/pom.xml | 9 +- .../org/openapitools/OpenAPI2SpringBoot.java | 3 +- .../org/openapitools/api/AnotherFakeApi.java | 8 +- .../api/AnotherFakeApiController.java | 33 +-- .../api/AnotherFakeApiDelegate.java | 22 +- .../java/org/openapitools/api/FakeApi.java | 72 +++-- .../openapitools/api/FakeApiController.java | 242 +-------------- .../org/openapitools/api/FakeApiDelegate.java | 132 +++++++-- .../api/FakeClassnameTestApi.java | 8 +- .../api/FakeClassnameTestApiController.java | 33 +-- .../api/FakeClassnameTestApiDelegate.java | 22 +- .../java/org/openapitools/api/PetApi.java | 36 ++- .../openapitools/api/PetApiController.java | 130 +-------- .../org/openapitools/api/PetApiDelegate.java | 105 ++++++- .../java/org/openapitools/api/StoreApi.java | 20 +- .../openapitools/api/StoreApiController.java | 72 +---- .../openapitools/api/StoreApiDelegate.java | 56 +++- .../java/org/openapitools/api/UserApi.java | 36 ++- .../openapitools/api/UserApiController.java | 119 +------- .../org/openapitools/api/UserApiDelegate.java | 66 ++++- .../CustomInstantDeserializer.java | 232 --------------- .../configuration/JacksonConfiguration.java | 23 -- .../OpenAPIDocumentationConfig.java | 5 +- .../model/AdditionalPropertiesClass.java | 16 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../openapitools/model/ArrayOfNumberOnly.java | 2 +- .../org/openapitools/model/ArrayTest.java | 6 +- .../org/openapitools/model/EnumArrays.java | 2 +- .../model/FileSchemaTestClass.java | 2 +- .../org/openapitools/model/FormatTest.java | 4 +- .../java/org/openapitools/model/MapTest.java | 8 +- ...ropertiesAndAdditionalPropertiesClass.java | 4 +- .../java/org/openapitools/model/Order.java | 2 +- .../main/java/org/openapitools/model/Pet.java | 4 +- .../openapitools/model/TypeHolderDefault.java | 2 +- .../openapitools/model/TypeHolderExample.java | 2 +- .../java/org/openapitools/model/XmlItem.java | 18 +- 71 files changed, 973 insertions(+), 2068 deletions(-) delete mode 100644 samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java delete mode 100644 samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java delete mode 100644 samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/JacksonConfiguration.java diff --git a/bin/configs/spring-boot-delegate.yaml b/bin/configs/spring-boot-delegate.yaml index 26b65d17ba74..162094128db3 100644 --- a/bin/configs/spring-boot-delegate.yaml +++ b/bin/configs/spring-boot-delegate.yaml @@ -5,5 +5,5 @@ templateDir: modules/openapi-generator/src/main/resources/JavaSpring additionalProperties: artifactId: springboot-delegate hideGenerationTimestamp: "true" - java8: "false" + java8: true delegatePattern: "true" diff --git a/bin/configs/spring-mvc.yaml b/bin/configs/spring-mvc.yaml index 2e8c1c718dec..8f16468573df 100644 --- a/bin/configs/spring-mvc.yaml +++ b/bin/configs/spring-mvc.yaml @@ -4,7 +4,7 @@ library: spring-mvc inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml templateDir: modules/openapi-generator/src/main/resources/JavaSpring additionalProperties: - java8: "false" + java8: true booleanGetterPrefix: get artifactId: spring-mvc-server hideGenerationTimestamp: "true" diff --git a/samples/server/petstore/spring-mvc/.openapi-generator/FILES b/samples/server/petstore/spring-mvc/.openapi-generator/FILES index 56bac36e8c9c..4b0ad04efe42 100644 --- a/samples/server/petstore/spring-mvc/.openapi-generator/FILES +++ b/samples/server/petstore/spring-mvc/.openapi-generator/FILES @@ -13,7 +13,6 @@ src/main/java/org/openapitools/api/StoreApi.java src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java src/main/java/org/openapitools/api/UserApiController.java -src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java src/main/java/org/openapitools/configuration/OpenAPIUiConfiguration.java diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index 49b9cce014cd..722935b3b1ac 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -123,9 +123,9 @@ ${springfox-version} - com.github.joschi.jackson - jackson-datatype-threetenbp - ${jackson-threetenbp-version} + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} org.openapitools @@ -152,7 +152,7 @@ - 1.7 + 1.8 ${java.version} ${java.version} 9.2.15.v20160210 diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java index 07b6801beb07..44f3e9bb93f2 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -7,20 +7,28 @@ import org.openapitools.model.Client; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * PATCH /another-fake/dummy : To test special tags * To test special tags and operation ID starting with number @@ -36,6 +44,18 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApiController.java index 731880309bfb..7e8132190d66 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -1,25 +1,9 @@ package org.openapitools.api; -import org.openapitools.model.Client; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/}") @@ -32,24 +16,9 @@ public AnotherFakeApiController(NativeWebRequest request) { this.request = request; } - /** - * PATCH /another-fake/dummy : To test special tags - * To test special tags and operation ID starting with number - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see AnotherFakeApi#call123testSpecialTags - */ - public ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"client\" : \"client\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java index f2f112c57500..11a5cf7b551a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApi.java @@ -8,29 +8,37 @@ import java.math.BigDecimal; import org.openapitools.model.Client; import org.openapitools.model.FileSchemaTestClass; -import org.threeten.bp.LocalDate; +import java.time.LocalDate; import java.util.Map; import org.openapitools.model.ModelApiResponse; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; import org.openapitools.model.OuterComposite; import org.springframework.core.io.Resource; import org.openapitools.model.User; import org.openapitools.model.XmlItem; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake", description = "the fake API") public interface FakeApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /fake/create_xml_item : creates an XmlItem * this route creates an XmlItem @@ -45,7 +53,10 @@ public interface FakeApi { value = "/fake/create_xml_item", consumes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" } ) - ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem); + default ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -62,7 +73,10 @@ public interface FakeApi { value = "/fake/outer/boolean", produces = { "*/*" } ) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body); + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -79,7 +93,19 @@ public interface FakeApi { value = "/fake/outer/composite", produces = { "*/*" } ) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body); + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { + String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }"; + ApiUtil.setExampleResponse(request, "*/*", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -96,7 +122,10 @@ public interface FakeApi { value = "/fake/outer/number", produces = { "*/*" } ) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body); + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -113,7 +142,10 @@ public interface FakeApi { value = "/fake/outer/string", produces = { "*/*" } ) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body); + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -130,7 +162,10 @@ public interface FakeApi { value = "/fake/body-with-file-schema", consumes = { "application/json" } ) - ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body); + default ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -147,7 +182,10 @@ public interface FakeApi { value = "/fake/body-with-query-params", consumes = { "application/json" } ) - ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -165,7 +203,19 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -199,16 +249,19 @@ public interface FakeApi { value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback); + default ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /fake : To test enum parameters * To test enum parameters * - * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -225,7 +278,10 @@ public interface FakeApi { value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString); + default ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -246,7 +302,10 @@ public interface FakeApi { @DeleteMapping( value = "/fake" ) - ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group); + default ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -262,7 +321,10 @@ public interface FakeApi { value = "/fake/inline-additionalProperties", consumes = { "application/json" } ) - ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param); + default ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -279,7 +341,10 @@ public interface FakeApi { value = "/fake/jsonFormData", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2); + default ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -299,7 +364,10 @@ public interface FakeApi { @PutMapping( value = "/fake/test-query-paramters" ) - ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context); + default ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -323,6 +391,18 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "multipart/form-data" } ) - ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata); + default ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java index 68f42954ab3b..1ac9ecd804c4 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeApiController.java @@ -1,35 +1,9 @@ package org.openapitools.api; -import java.math.BigDecimal; -import org.openapitools.model.Client; -import org.openapitools.model.FileSchemaTestClass; -import org.threeten.bp.LocalDate; -import java.util.Map; -import org.openapitools.model.ModelApiResponse; -import org.threeten.bp.OffsetDateTime; -import org.openapitools.model.OuterComposite; -import org.springframework.core.io.Resource; -import org.openapitools.model.User; -import org.openapitools.model.XmlItem; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/}") @@ -42,251 +16,9 @@ public FakeApiController(NativeWebRequest request) { this.request = request; } - /** - * POST /fake/create_xml_item : creates an XmlItem - * this route creates an XmlItem - * - * @param xmlItem XmlItem Body (required) - * @return successful operation (status code 200) - * @see FakeApi#createXmlItem - */ - public ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/boolean - * Test serialization of outer boolean types - * - * @param body Input boolean as post body (optional) - * @return Output boolean (status code 200) - * @see FakeApi#fakeOuterBooleanSerialize - */ - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/composite - * Test serialization of object with outer number type - * - * @param body Input composite as post body (optional) - * @return Output composite (status code 200) - * @see FakeApi#fakeOuterCompositeSerialize - */ - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { - String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }"; - ApiUtil.setExampleResponse(request, "*/*", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/number - * Test serialization of outer number types - * - * @param body Input number as post body (optional) - * @return Output number (status code 200) - * @see FakeApi#fakeOuterNumberSerialize - */ - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/outer/string - * Test serialization of outer string types - * - * @param body Input string as post body (optional) - * @return Output string (status code 200) - * @see FakeApi#fakeOuterStringSerialize - */ - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /fake/body-with-file-schema - * For this test, the body for this request much reference a schema named `File`. - * - * @param body (required) - * @return Success (status code 200) - * @see FakeApi#testBodyWithFileSchema - */ - public ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /fake/body-with-query-params - * - * @param query (required) - * @param body (required) - * @return Success (status code 200) - * @see FakeApi#testBodyWithQueryParams - */ - public ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PATCH /fake : To test \"client\" model - * To test \"client\" model - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see FakeApi#testClientModel - */ - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"client\" : \"client\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake : Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @return Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see FakeApi#testEndpointParameters - */ - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /fake : To test enum parameters - * To test enum parameters - * - * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<String>()) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<String>()) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param enumFormStringArray Form parameter enum test (string array) (optional, default to $) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @return Invalid request (status code 400) - * or Not found (status code 404) - * @see FakeApi#testEnumParameters - */ - public ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * DELETE /fake : Fake endpoint to test group parameters (optional) - * Fake endpoint to test group parameters (optional) - * - * @param requiredStringGroup Required String in group parameters (required) - * @param requiredBooleanGroup Required Boolean in group parameters (required) - * @param requiredInt64Group Required Integer in group parameters (required) - * @param stringGroup String in group parameters (optional) - * @param booleanGroup Boolean in group parameters (optional) - * @param int64Group Integer in group parameters (optional) - * @return Someting wrong (status code 400) - * @see FakeApi#testGroupParameters - */ - public ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/inline-additionalProperties : test inline additionalProperties - * - * @param param request body (required) - * @return successful operation (status code 200) - * @see FakeApi#testInlineAdditionalProperties - */ - public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /fake/jsonFormData : test json serialization of form data - * - * @param param field1 (required) - * @param param2 field2 (required) - * @return successful operation (status code 200) - * @see FakeApi#testJsonFormData - */ - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /fake/test-query-paramters - * To test the collection format in query parameters - * - * @param pipe (required) - * @param ioutil (required) - * @param http (required) - * @param url (required) - * @param context (required) - * @return Success (status code 200) - * @see FakeApi#testQueryParameterCollectionFormat - */ - public ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /fake/{petId}/uploadImageWithRequiredFile : uploads an image (required) - * - * @param petId ID of pet to update (required) - * @param requiredFile file to upload (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @return successful operation (status code 200) - * @see FakeApi#uploadFileWithRequiredFile - */ - public ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 723fc9f62ac5..5742965028b0 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -7,20 +7,28 @@ import org.openapitools.model.Client; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * PATCH /fake_classname_test : To test class name in snake case * To test class name in snake case @@ -38,6 +46,18 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 90b1fcb28b5c..68f9c4233e88 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -1,25 +1,9 @@ package org.openapitools.api; -import org.openapitools.model.Client; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/}") @@ -32,24 +16,9 @@ public FakeClassnameTestApiController(NativeWebRequest request) { this.request = request; } - /** - * PATCH /fake_classname_test : To test class name in snake case - * To test class name in snake case - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see FakeClassnameTestApi#testClassname - */ - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"client\" : \"client\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java index 7ab2f6e9d5f7..51080bb7d32b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApi.java @@ -10,20 +10,28 @@ import org.springframework.core.io.Resource; import java.util.Set; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "pet", description = "the pet API") public interface PetApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /pet : Add a new pet to the store * @@ -44,7 +52,10 @@ public interface PetApi { value = "/pet", consumes = { "application/json", "application/xml" } ) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); + default ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -67,7 +78,10 @@ public interface PetApi { @DeleteMapping( value = "/pet/{petId}" ) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + default ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -91,7 +105,24 @@ public interface PetApi { value = "/pet/findByStatus", produces = { "application/xml", "application/json" } ) - ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); + default ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -116,7 +147,24 @@ public interface PetApi { value = "/pet/findByTags", produces = { "application/xml", "application/json" } ) - ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags); + default ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -139,7 +187,24 @@ public interface PetApi { value = "/pet/{petId}", produces = { "application/xml", "application/json" } ) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); + default ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -166,7 +231,10 @@ public interface PetApi { value = "/pet", consumes = { "application/json", "application/xml" } ) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); + default ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -189,7 +257,10 @@ public interface PetApi { value = "/pet/{petId}", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status); + default ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -213,6 +284,18 @@ public interface PetApi { produces = { "application/json" }, consumes = { "multipart/form-data" } ) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file); + default ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApiController.java index ac991356a7a6..1485b58cb3ec 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/PetApiController.java @@ -1,28 +1,9 @@ package org.openapitools.api; -import org.openapitools.model.ModelApiResponse; -import org.openapitools.model.Pet; -import org.springframework.core.io.Resource; -import java.util.Set; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/}") @@ -35,161 +16,9 @@ public PetApiController(NativeWebRequest request) { this.request = request; } - /** - * POST /pet : Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return successful operation (status code 200) - * or Invalid input (status code 405) - * @see PetApi#addPet - */ - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * DELETE /pet/{petId} : Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return successful operation (status code 200) - * or Invalid pet value (status code 400) - * @see PetApi#deletePet - */ - public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /pet/findByStatus : Finds Pets by status - * Multiple status values can be provided with comma separated strings - * - * @param status Status values that need to be considered for filter (required) - * @return successful operation (status code 200) - * or Invalid status value (status code 400) - * @see PetApi#findPetsByStatus - */ - public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 doggie aeiou aeiou "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /pet/findByTags : Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @param tags Tags to filter by (required) - * @return successful operation (status code 200) - * or Invalid tag value (status code 400) - * @deprecated - * @see PetApi#findPetsByTags - */ - public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 doggie aeiou aeiou "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /pet/{petId} : Find pet by ID - * Returns a single pet - * - * @param petId ID of pet to return (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Pet not found (status code 404) - * @see PetApi#getPetById - */ - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 doggie aeiou aeiou "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /pet : Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Pet not found (status code 404) - * or Validation exception (status code 405) - * @see PetApi#updatePet - */ - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /pet/{petId} : Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return Invalid input (status code 405) - * @see PetApi#updatePetWithForm - */ - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /pet/{petId}/uploadImage : uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return successful operation (status code 200) - * @see PetApi#uploadFile - */ - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java index 0128cb2d54b8..831650ae3d69 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApi.java @@ -8,20 +8,28 @@ import java.util.Map; import org.openapitools.model.Order; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "store", description = "the store API") public interface StoreApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * DELETE /store/order/{order_id} : Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -37,7 +45,10 @@ public interface StoreApi { @DeleteMapping( value = "/store/order/{order_id}" ) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); + default ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -55,7 +66,10 @@ public interface StoreApi { value = "/store/inventory", produces = { "application/json" } ) - ResponseEntity> getInventory(); + default ResponseEntity> getInventory() { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -76,7 +90,24 @@ public interface StoreApi { value = "/store/order/{order_id}", produces = { "application/xml", "application/json" } ) - ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); + default ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -94,6 +125,23 @@ public interface StoreApi { value = "/store/order", produces = { "application/xml", "application/json" } ) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); + default ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApiController.java index b03098aa747f..3a8489c4176d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/StoreApiController.java @@ -1,26 +1,9 @@ package org.openapitools.api; -import java.util.Map; -import org.openapitools.model.Order; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/}") @@ -33,82 +16,9 @@ public StoreApiController(NativeWebRequest request) { this.request = request; } - /** - * DELETE /store/order/{order_id} : Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @param orderId ID of the order that needs to be deleted (required) - * @return Invalid ID supplied (status code 400) - * or Order not found (status code 404) - * @see StoreApi#deleteOrder - */ - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /store/inventory : Returns pet inventories by status - * Returns a map of status codes to quantities - * - * @return successful operation (status code 200) - * @see StoreApi#getInventory - */ - public ResponseEntity> getInventory() { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /store/order/{order_id} : Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @param orderId ID of pet that needs to be fetched (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Order not found (status code 404) - * @see StoreApi#getOrderById - */ - public ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /store/order : Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return successful operation (status code 200) - * or Invalid Order (status code 400) - * @see StoreApi#placeOrder - */ - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java index e1d4245a6b15..f6b591946bc3 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApi.java @@ -8,20 +8,28 @@ import java.util.List; import org.openapitools.model.User; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import javax.validation.Valid; import javax.validation.constraints.*; import java.util.List; import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Validated @Api(value = "user", description = "the user API") public interface UserApi { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /user : Create user * This can only be done by the logged in user. @@ -35,7 +43,10 @@ public interface UserApi { @PostMapping( value = "/user" ) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -50,7 +61,10 @@ public interface UserApi { @PostMapping( value = "/user/createWithArray" ) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); + default ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -65,7 +79,10 @@ public interface UserApi { @PostMapping( value = "/user/createWithList" ) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); + default ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -83,7 +100,10 @@ public interface UserApi { @DeleteMapping( value = "/user/{username}" ) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); + default ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -103,7 +123,24 @@ public interface UserApi { value = "/user/{username}", produces = { "application/xml", "application/json" } ) - ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username); + default ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123 "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -122,7 +159,10 @@ public interface UserApi { value = "/user/login", produces = { "application/xml", "application/json" } ) - ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); + default ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -136,7 +176,10 @@ public interface UserApi { @GetMapping( value = "/user/logout" ) - ResponseEntity logoutUser(); + default ResponseEntity logoutUser() { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** @@ -155,6 +198,9 @@ public interface UserApi { @PutMapping( value = "/user/{username}" ) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApiController.java index 24445f783726..85e906911582 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/api/UserApiController.java @@ -1,26 +1,9 @@ package org.openapitools.api; -import java.util.List; -import org.openapitools.model.User; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/}") @@ -33,121 +16,9 @@ public UserApiController(NativeWebRequest request) { this.request = request; } - /** - * POST /user : Create user - * This can only be done by the logged in user. - * - * @param body Created user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUser - */ - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /user/createWithArray : Creates list of users with given input array - * - * @param body List of user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUsersWithArrayInput - */ - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * POST /user/createWithList : Creates list of users with given input array - * - * @param body List of user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUsersWithListInput - */ - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * DELETE /user/{username} : Delete user - * This can only be done by the logged in user. - * - * @param username The name that needs to be deleted (required) - * @return Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#deleteUser - */ - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /user/{username} : Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return successful operation (status code 200) - * or Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#getUserByName - */ - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username) { - for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { - if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }"; - ApiUtil.setExampleResponse(request, "application/json", exampleString); - break; - } - if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { - String exampleString = " 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123 "; - ApiUtil.setExampleResponse(request, "application/xml", exampleString); - break; - } - } - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /user/login : Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return successful operation (status code 200) - * or Invalid username/password supplied (status code 400) - * @see UserApi#loginUser - */ - public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * GET /user/logout : Logs out current logged in user session - * - * @return successful operation (status code 200) - * @see UserApi#logoutUser - */ - public ResponseEntity logoutUser() { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - - } - - /** - * PUT /user/{username} : Updated user - * This can only be done by the logged in user. - * - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return Invalid user supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#updateUser - */ - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { - return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); - + @Override + public Optional getRequest() { + return Optional.ofNullable(request); } } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java deleted file mode 100644 index 8f936b311447..000000000000 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java +++ /dev/null @@ -1,232 +0,0 @@ -package org.openapitools.configuration; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonTokenId; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; -import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; -import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; -import com.fasterxml.jackson.datatype.threetenbp.function.Function; -import org.threeten.bp.DateTimeException; -import org.threeten.bp.DateTimeUtils; -import org.threeten.bp.Instant; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZoneId; -import org.threeten.bp.ZonedDateTime; -import org.threeten.bp.format.DateTimeFormatter; -import org.threeten.bp.temporal.Temporal; -import org.threeten.bp.temporal.TemporalAccessor; - -import java.io.IOException; -import java.math.BigDecimal; - -/** - * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. - * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. - * - * @author Nick Williams - */ -public class CustomInstantDeserializer - extends ThreeTenDateTimeDeserializerBase { - private static final long serialVersionUID = 1L; - - public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( - Instant.class, DateTimeFormatter.ISO_INSTANT, - new Function() { - @Override - public Instant apply(TemporalAccessor temporalAccessor) { - return Instant.from(temporalAccessor); - } - }, - new Function() { - @Override - public Instant apply(FromIntegerArguments a) { - return Instant.ofEpochMilli(a.value); - } - }, - new Function() { - @Override - public Instant apply(FromDecimalArguments a) { - return Instant.ofEpochSecond(a.integer, a.fraction); - } - }, - null - ); - - public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( - OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, - new Function() { - @Override - public OffsetDateTime apply(TemporalAccessor temporalAccessor) { - return OffsetDateTime.from(temporalAccessor); - } - }, - new Function() { - @Override - public OffsetDateTime apply(FromIntegerArguments a) { - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); - } - }, - new Function() { - @Override - public OffsetDateTime apply(FromDecimalArguments a) { - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); - } - }, - new BiFunction() { - @Override - public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { - return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); - } - } - ); - - public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( - ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, - new Function() { - @Override - public ZonedDateTime apply(TemporalAccessor temporalAccessor) { - return ZonedDateTime.from(temporalAccessor); - } - }, - new Function() { - @Override - public ZonedDateTime apply(FromIntegerArguments a) { - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); - } - }, - new Function() { - @Override - public ZonedDateTime apply(FromDecimalArguments a) { - return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); - } - }, - new BiFunction() { - @Override - public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { - return zonedDateTime.withZoneSameInstant(zoneId); - } - } - ); - - protected final Function fromMilliseconds; - - protected final Function fromNanoseconds; - - protected final Function parsedToValue; - - protected final BiFunction adjust; - - protected CustomInstantDeserializer(Class supportedType, - DateTimeFormatter parser, - Function parsedToValue, - Function fromMilliseconds, - Function fromNanoseconds, - BiFunction adjust) { - super(supportedType, parser); - this.parsedToValue = parsedToValue; - this.fromMilliseconds = fromMilliseconds; - this.fromNanoseconds = fromNanoseconds; - this.adjust = adjust == null ? new BiFunction() { - @Override - public T apply(T t, ZoneId zoneId) { - return t; - } - } : adjust; - } - - @SuppressWarnings("unchecked") - protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { - super((Class) base.handledType(), f); - parsedToValue = base.parsedToValue; - fromMilliseconds = base.fromMilliseconds; - fromNanoseconds = base.fromNanoseconds; - adjust = base.adjust; - } - - @Override - protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { - if (dtf == _formatter) { - return this; - } - return new CustomInstantDeserializer(this, dtf); - } - - @Override - public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { - //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only - //string values have to be adjusted to the configured TZ. - switch (parser.getCurrentTokenId()) { - case JsonTokenId.ID_NUMBER_FLOAT: { - BigDecimal value = parser.getDecimalValue(); - long seconds = value.longValue(); - int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); - return fromNanoseconds.apply(new FromDecimalArguments( - seconds, nanoseconds, getZone(context))); - } - - case JsonTokenId.ID_NUMBER_INT: { - long timestamp = parser.getLongValue(); - if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { - return this.fromNanoseconds.apply(new FromDecimalArguments( - timestamp, 0, this.getZone(context) - )); - } - return this.fromMilliseconds.apply(new FromIntegerArguments( - timestamp, this.getZone(context) - )); - } - - case JsonTokenId.ID_STRING: { - String string = parser.getText().trim(); - if (string.length() == 0) { - return null; - } - if (string.endsWith("+0000")) { - string = string.substring(0, string.length() - 5) + "Z"; - } - T value; - try { - TemporalAccessor acc = _formatter.parse(string); - value = parsedToValue.apply(acc); - if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { - return adjust.apply(value, this.getZone(context)); - } - } catch (DateTimeException e) { - throw _peelDTE(e); - } - return value; - } - } - throw context.mappingException("Expected type float, integer, or string."); - } - - private ZoneId getZone(DeserializationContext context) { - // Instants are always in UTC, so don't waste compute cycles - return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); - } - - private static class FromIntegerArguments { - public final long value; - public final ZoneId zoneId; - - private FromIntegerArguments(long value, ZoneId zoneId) { - this.value = value; - this.zoneId = zoneId; - } - } - - private static class FromDecimalArguments { - public final long integer; - public final int fraction; - public final ZoneId zoneId; - - private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { - this.integer = integer; - this.fraction = fraction; - this.zoneId = zoneId; - } - } -} diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java index 41d0edf11651..3df5ef9f3c34 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java @@ -40,8 +40,9 @@ public Docket customImplementation(ServletContext servletContext, @Value("${open .select() .apis(RequestHandlerSelectors.basePackage("org.openapitools.api")) .build() - .directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class) - .directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class) + .pathProvider(new BasePathAwareRelativePathProvider(servletContext, basePath)) + .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIUiConfiguration.java index 15f4ddf5ae18..e61611e3b14f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/configuration/OpenAPIUiConfiguration.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; -import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; import org.openapitools.jackson.nullable.JsonNullableModule; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @@ -16,9 +15,6 @@ import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; -import org.threeten.bp.Instant; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZonedDateTime; import java.util.List; @@ -73,14 +69,10 @@ public void addCorsMappings(CorsRegistry registry) { @Bean public Jackson2ObjectMapperBuilder builder() { - ThreeTenModule module = new ThreeTenModule(); - module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); - module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); - module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); return new Jackson2ObjectMapperBuilder() .indentOutput(true) .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) - .modulesToInstall(module, new JsonNullableModule()) + .modulesToInstall(new JsonNullableModule()) .dateFormat(new RFC3339DateFormat()); } diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java index ce47917ea6ee..7b6f5ac16c76 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -68,7 +68,7 @@ public AdditionalPropertiesClass mapString(Map mapString) { public AdditionalPropertiesClass putMapStringItem(String key, String mapStringItem) { if (this.mapString == null) { - this.mapString = new HashMap(); + this.mapString = new HashMap<>(); } this.mapString.put(key, mapStringItem); return this; @@ -96,7 +96,7 @@ public AdditionalPropertiesClass mapNumber(Map mapNumber) { public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumberItem) { if (this.mapNumber == null) { - this.mapNumber = new HashMap(); + this.mapNumber = new HashMap<>(); } this.mapNumber.put(key, mapNumberItem); return this; @@ -125,7 +125,7 @@ public AdditionalPropertiesClass mapInteger(Map mapInteger) { public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntegerItem) { if (this.mapInteger == null) { - this.mapInteger = new HashMap(); + this.mapInteger = new HashMap<>(); } this.mapInteger.put(key, mapIntegerItem); return this; @@ -153,7 +153,7 @@ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBooleanItem) { if (this.mapBoolean == null) { - this.mapBoolean = new HashMap(); + this.mapBoolean = new HashMap<>(); } this.mapBoolean.put(key, mapBooleanItem); return this; @@ -181,7 +181,7 @@ public AdditionalPropertiesClass mapArrayInteger(Map> mapA public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List mapArrayIntegerItem) { if (this.mapArrayInteger == null) { - this.mapArrayInteger = new HashMap>(); + this.mapArrayInteger = new HashMap<>(); } this.mapArrayInteger.put(key, mapArrayIntegerItem); return this; @@ -210,7 +210,7 @@ public AdditionalPropertiesClass mapArrayAnytype(Map> mapAr public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List mapArrayAnytypeItem) { if (this.mapArrayAnytype == null) { - this.mapArrayAnytype = new HashMap>(); + this.mapArrayAnytype = new HashMap<>(); } this.mapArrayAnytype.put(key, mapArrayAnytypeItem); return this; @@ -239,7 +239,7 @@ public AdditionalPropertiesClass mapMapString(Map> m public AdditionalPropertiesClass putMapMapStringItem(String key, Map mapMapStringItem) { if (this.mapMapString == null) { - this.mapMapString = new HashMap>(); + this.mapMapString = new HashMap<>(); } this.mapMapString.put(key, mapMapStringItem); return this; @@ -268,7 +268,7 @@ public AdditionalPropertiesClass mapMapAnytype(Map> public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map mapMapAnytypeItem) { if (this.mapMapAnytype == null) { - this.mapMapAnytype = new HashMap>(); + this.mapMapAnytype = new HashMap<>(); } this.mapMapAnytype.put(key, mapMapAnytypeItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 412feee52305..9fa32d2ea9cd 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -30,7 +30,7 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList>(); + this.arrayArrayNumber = new ArrayList<>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java index f6f314a4f1bf..7910abcc6964 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -30,7 +30,7 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList(); + this.arrayNumber = new ArrayList<>(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayTest.java index 908810d635af..cb245ac0b603 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/ArrayTest.java @@ -38,7 +38,7 @@ public ArrayTest arrayOfString(List arrayOfString) { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList(); + this.arrayOfString = new ArrayList<>(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -66,7 +66,7 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList>(); + this.arrayArrayOfInteger = new ArrayList<>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -95,7 +95,7 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList>(); + this.arrayArrayOfModel = new ArrayList<>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/EnumArrays.java index dd1e1b124701..618b78fcbc5a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/EnumArrays.java @@ -123,7 +123,7 @@ public EnumArrays arrayEnum(List arrayEnum) { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList(); + this.arrayEnum = new ArrayList<>(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FileSchemaTestClass.java index d01c6935fc52..2e1fa7540451 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FileSchemaTestClass.java @@ -53,7 +53,7 @@ public FileSchemaTestClass files(List files) { public FileSchemaTestClass addFilesItem(java.io.File filesItem) { if (this.files == null) { - this.files = new ArrayList(); + this.files = new ArrayList<>(); } this.files.add(filesItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java index 8a8c11a3e5e5..f75829b436e6 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/FormatTest.java @@ -6,10 +6,10 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; import java.util.UUID; import org.springframework.core.io.Resource; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MapTest.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MapTest.java index e8ed4979406a..fbb4966cc6ca 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MapTest.java @@ -78,7 +78,7 @@ public MapTest mapMapOfString(Map> mapMapOfString) { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap>(); + this.mapMapOfString = new HashMap<>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -107,7 +107,7 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap(); + this.mapOfEnumString = new HashMap<>(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; @@ -135,7 +135,7 @@ public MapTest directMap(Map directMap) { public MapTest putDirectMapItem(String key, Boolean directMapItem) { if (this.directMap == null) { - this.directMap = new HashMap(); + this.directMap = new HashMap<>(); } this.directMap.put(key, directMapItem); return this; @@ -163,7 +163,7 @@ public MapTest indirectMap(Map indirectMap) { public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { if (this.indirectMap == null) { - this.indirectMap = new HashMap(); + this.indirectMap = new HashMap<>(); } this.indirectMap.put(key, indirectMapItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 6e2f93546ebd..2cab02c3d081 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -5,12 +5,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.openapitools.model.Animal; -import org.threeten.bp.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; @@ -82,7 +82,7 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.map.put(key, mapItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Order.java index c7350c2eaa0f..c10da34792ca 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Order.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Pet.java index 61cdc3830f11..1c2cd719532a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/Pet.java @@ -34,7 +34,7 @@ public class Pet { @JsonProperty("photoUrls") @Valid - private Set photoUrls = new LinkedHashSet(); + private Set photoUrls = new LinkedHashSet<>(); @JsonProperty("tags") @Valid @@ -175,7 +175,7 @@ public Pet tags(List tags) { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList(); + this.tags = new ArrayList<>(); } this.tags.add(tagsItem); return this; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderDefault.java index 3b07a1358d82..70f7a789f6b8 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderDefault.java @@ -33,7 +33,7 @@ public class TypeHolderDefault { @JsonProperty("array_item") @Valid - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderDefault stringItem(String stringItem) { this.stringItem = stringItem; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderExample.java index aef218572eae..56092259288e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/TypeHolderExample.java @@ -36,7 +36,7 @@ public class TypeHolderExample { @JsonProperty("array_item") @Valid - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderExample stringItem(String stringItem) { this.stringItem = stringItem; diff --git a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/XmlItem.java index 820c082d2859..75eb7b6f26db 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/spring-mvc/src/main/java/org/openapitools/model/XmlItem.java @@ -203,7 +203,7 @@ public XmlItem wrappedArray(List wrappedArray) { public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { if (this.wrappedArray == null) { - this.wrappedArray = new ArrayList(); + this.wrappedArray = new ArrayList<>(); } this.wrappedArray.add(wrappedArrayItem); return this; @@ -312,7 +312,7 @@ public XmlItem nameArray(List nameArray) { public XmlItem addNameArrayItem(Integer nameArrayItem) { if (this.nameArray == null) { - this.nameArray = new ArrayList(); + this.nameArray = new ArrayList<>(); } this.nameArray.add(nameArrayItem); return this; @@ -340,7 +340,7 @@ public XmlItem nameWrappedArray(List nameWrappedArray) { public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { if (this.nameWrappedArray == null) { - this.nameWrappedArray = new ArrayList(); + this.nameWrappedArray = new ArrayList<>(); } this.nameWrappedArray.add(nameWrappedArrayItem); return this; @@ -449,7 +449,7 @@ public XmlItem prefixArray(List prefixArray) { public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { if (this.prefixArray == null) { - this.prefixArray = new ArrayList(); + this.prefixArray = new ArrayList<>(); } this.prefixArray.add(prefixArrayItem); return this; @@ -477,7 +477,7 @@ public XmlItem prefixWrappedArray(List prefixWrappedArray) { public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { if (this.prefixWrappedArray == null) { - this.prefixWrappedArray = new ArrayList(); + this.prefixWrappedArray = new ArrayList<>(); } this.prefixWrappedArray.add(prefixWrappedArrayItem); return this; @@ -586,7 +586,7 @@ public XmlItem namespaceArray(List namespaceArray) { public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { if (this.namespaceArray == null) { - this.namespaceArray = new ArrayList(); + this.namespaceArray = new ArrayList<>(); } this.namespaceArray.add(namespaceArrayItem); return this; @@ -614,7 +614,7 @@ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { if (this.namespaceWrappedArray == null) { - this.namespaceWrappedArray = new ArrayList(); + this.namespaceWrappedArray = new ArrayList<>(); } this.namespaceWrappedArray.add(namespaceWrappedArrayItem); return this; @@ -723,7 +723,7 @@ public XmlItem prefixNsArray(List prefixNsArray) { public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { if (this.prefixNsArray == null) { - this.prefixNsArray = new ArrayList(); + this.prefixNsArray = new ArrayList<>(); } this.prefixNsArray.add(prefixNsArrayItem); return this; @@ -751,7 +751,7 @@ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { if (this.prefixNsWrappedArray == null) { - this.prefixNsWrappedArray = new ArrayList(); + this.prefixNsWrappedArray = new ArrayList<>(); } this.prefixNsWrappedArray.add(prefixNsWrappedArrayItem); return this; diff --git a/samples/server/petstore/springboot-delegate/.openapi-generator/FILES b/samples/server/petstore/springboot-delegate/.openapi-generator/FILES index 751215bab5e1..8c36406da484 100644 --- a/samples/server/petstore/springboot-delegate/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-delegate/.openapi-generator/FILES @@ -21,9 +21,7 @@ src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java -src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java src/main/java/org/openapitools/configuration/HomeController.java -src/main/java/org/openapitools/configuration/JacksonConfiguration.java src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java src/main/java/org/openapitools/model/AdditionalPropertiesAnyType.java src/main/java/org/openapitools/model/AdditionalPropertiesArray.java diff --git a/samples/server/petstore/springboot-delegate/pom.xml b/samples/server/petstore/springboot-delegate/pom.xml index 83b61b77934c..01f5ccf7905a 100644 --- a/samples/server/petstore/springboot-delegate/pom.xml +++ b/samples/server/petstore/springboot-delegate/pom.xml @@ -6,7 +6,7 @@ springboot-delegate 1.0.0 - 1.7 + 1.8 ${java.version} ${java.version} 2.8.0 @@ -14,7 +14,7 @@ org.springframework.boot spring-boot-starter-parent - 1.5.12.RELEASE + 2.0.1.RELEASE src/main/java @@ -54,9 +54,8 @@ 2.2.11 - com.github.joschi.jackson - jackson-datatype-threetenbp - 2.8.4 + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 org.openapitools diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/OpenAPI2SpringBoot.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/OpenAPI2SpringBoot.java index b7af36b6bbd3..7cad28eed8ac 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/OpenAPI2SpringBoot.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/OpenAPI2SpringBoot.java @@ -10,7 +10,6 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @SpringBootApplication @ComponentScan(basePackages = {"org.openapitools", "org.openapitools.api" , "org.openapitools.configuration"}) @@ -39,7 +38,7 @@ public int getExitCode() { @Bean public WebMvcConfigurer webConfigurer() { - return new WebMvcConfigurerAdapter() { + return new WebMvcConfigurer() { /*@Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java index 07b6801beb07..d0977d683dfb 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -21,6 +21,10 @@ @Api(value = "another-fake", description = "the another-fake API") public interface AnotherFakeApi { + default AnotherFakeApiDelegate getDelegate() { + return new AnotherFakeApiDelegate() {}; + } + /** * PATCH /another-fake/dummy : To test special tags * To test special tags and operation ID starting with number @@ -36,6 +40,8 @@ public interface AnotherFakeApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + return getDelegate().call123testSpecialTags(body); + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java index 659e82778aa4..df11134c8067 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiController.java @@ -1,24 +1,8 @@ package org.openapitools.api; -import org.openapitools.model.Client; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -27,19 +11,12 @@ public class AnotherFakeApiController implements AnotherFakeApi { private final AnotherFakeApiDelegate delegate; public AnotherFakeApiController(@org.springframework.beans.factory.annotation.Autowired(required = false) AnotherFakeApiDelegate delegate) { - this.delegate = delegate; + this.delegate = Optional.ofNullable(delegate).orElse(new AnotherFakeApiDelegate() {}); } - /** - * PATCH /another-fake/dummy : To test special tags - * To test special tags and operation ID starting with number - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see AnotherFakeApi#call123testSpecialTags - */ - public ResponseEntity call123testSpecialTags(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - return delegate.call123testSpecialTags(body); + @Override + public AnotherFakeApiDelegate getDelegate() { + return delegate; } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java index d17e376d976f..7e6ac74b30f4 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java @@ -2,11 +2,15 @@ import org.openapitools.model.Client; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; +import java.util.Optional; /** * A delegate to be called by the {@link AnotherFakeApiController}}. @@ -15,6 +19,10 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public interface AnotherFakeApiDelegate { + default Optional getRequest() { + return Optional.empty(); + } + /** * PATCH /another-fake/dummy : To test special tags * To test special tags and operation ID starting with number @@ -23,6 +31,18 @@ public interface AnotherFakeApiDelegate { * @return successful operation (status code 200) * @see AnotherFakeApi#call123testSpecialTags */ - ResponseEntity call123testSpecialTags(Client body); + default ResponseEntity call123testSpecialTags(Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java index f2f112c57500..2c6f9356ff22 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java @@ -8,10 +8,10 @@ import java.math.BigDecimal; import org.openapitools.model.Client; import org.openapitools.model.FileSchemaTestClass; -import org.threeten.bp.LocalDate; +import java.time.LocalDate; import java.util.Map; import org.openapitools.model.ModelApiResponse; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; import org.openapitools.model.OuterComposite; import org.springframework.core.io.Resource; import org.openapitools.model.User; @@ -31,6 +31,10 @@ @Api(value = "fake", description = "the fake API") public interface FakeApi { + default FakeApiDelegate getDelegate() { + return new FakeApiDelegate() {}; + } + /** * POST /fake/create_xml_item : creates an XmlItem * this route creates an XmlItem @@ -45,7 +49,9 @@ public interface FakeApi { value = "/fake/create_xml_item", consumes = { "application/xml", "application/xml; charset=utf-8", "application/xml; charset=utf-16", "text/xml", "text/xml; charset=utf-8", "text/xml; charset=utf-16" } ) - ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem); + default ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem) { + return getDelegate().createXmlItem(xmlItem); + } /** @@ -62,7 +68,9 @@ public interface FakeApi { value = "/fake/outer/boolean", produces = { "*/*" } ) - ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body); + default ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { + return getDelegate().fakeOuterBooleanSerialize(body); + } /** @@ -79,7 +87,9 @@ public interface FakeApi { value = "/fake/outer/composite", produces = { "*/*" } ) - ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body); + default ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { + return getDelegate().fakeOuterCompositeSerialize(body); + } /** @@ -96,7 +106,9 @@ public interface FakeApi { value = "/fake/outer/number", produces = { "*/*" } ) - ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body); + default ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { + return getDelegate().fakeOuterNumberSerialize(body); + } /** @@ -113,7 +125,9 @@ public interface FakeApi { value = "/fake/outer/string", produces = { "*/*" } ) - ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body); + default ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { + return getDelegate().fakeOuterStringSerialize(body); + } /** @@ -130,7 +144,9 @@ public interface FakeApi { value = "/fake/body-with-file-schema", consumes = { "application/json" } ) - ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body); + default ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body) { + return getDelegate().testBodyWithFileSchema(body); + } /** @@ -147,7 +163,9 @@ public interface FakeApi { value = "/fake/body-with-query-params", consumes = { "application/json" } ) - ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body) { + return getDelegate().testBodyWithQueryParams(query, body); + } /** @@ -165,7 +183,9 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + return getDelegate().testClientModel(body); + } /** @@ -199,16 +219,18 @@ public interface FakeApi { value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback); + default ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback) { + return getDelegate().testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } /** * GET /fake : To test enum parameters * To test enum parameters * - * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -225,7 +247,9 @@ public interface FakeApi { value = "/fake", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString); + default ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString) { + return getDelegate().testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } /** @@ -246,7 +270,9 @@ public interface FakeApi { @DeleteMapping( value = "/fake" ) - ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group); + default ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group) { + return getDelegate().testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } /** @@ -262,7 +288,9 @@ public interface FakeApi { value = "/fake/inline-additionalProperties", consumes = { "application/json" } ) - ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param); + default ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param) { + return getDelegate().testInlineAdditionalProperties(param); + } /** @@ -279,7 +307,9 @@ public interface FakeApi { value = "/fake/jsonFormData", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2); + default ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2) { + return getDelegate().testJsonFormData(param, param2); + } /** @@ -299,7 +329,9 @@ public interface FakeApi { @PutMapping( value = "/fake/test-query-paramters" ) - ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context); + default ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context) { + return getDelegate().testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } /** @@ -323,6 +355,8 @@ public interface FakeApi { produces = { "application/json" }, consumes = { "multipart/form-data" } ) - ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata); + default ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata) { + return getDelegate().uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java index d61d01c66ba6..6b22c1aba661 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiController.java @@ -1,34 +1,8 @@ package org.openapitools.api; -import java.math.BigDecimal; -import org.openapitools.model.Client; -import org.openapitools.model.FileSchemaTestClass; -import org.threeten.bp.LocalDate; -import java.util.Map; -import org.openapitools.model.ModelApiResponse; -import org.threeten.bp.OffsetDateTime; -import org.openapitools.model.OuterComposite; -import org.springframework.core.io.Resource; -import org.openapitools.model.User; -import org.openapitools.model.XmlItem; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -37,218 +11,12 @@ public class FakeApiController implements FakeApi { private final FakeApiDelegate delegate; public FakeApiController(@org.springframework.beans.factory.annotation.Autowired(required = false) FakeApiDelegate delegate) { - this.delegate = delegate; - } - - /** - * POST /fake/create_xml_item : creates an XmlItem - * this route creates an XmlItem - * - * @param xmlItem XmlItem Body (required) - * @return successful operation (status code 200) - * @see FakeApi#createXmlItem - */ - public ResponseEntity createXmlItem(@ApiParam(value = "XmlItem Body" ,required=true ) @Valid @RequestBody XmlItem xmlItem) { - return delegate.createXmlItem(xmlItem); - } - - /** - * POST /fake/outer/boolean - * Test serialization of outer boolean types - * - * @param body Input boolean as post body (optional) - * @return Output boolean (status code 200) - * @see FakeApi#fakeOuterBooleanSerialize - */ - public ResponseEntity fakeOuterBooleanSerialize(@ApiParam(value = "Input boolean as post body" ) @Valid @RequestBody(required = false) Boolean body) { - return delegate.fakeOuterBooleanSerialize(body); - } - - /** - * POST /fake/outer/composite - * Test serialization of object with outer number type - * - * @param body Input composite as post body (optional) - * @return Output composite (status code 200) - * @see FakeApi#fakeOuterCompositeSerialize - */ - public ResponseEntity fakeOuterCompositeSerialize(@ApiParam(value = "Input composite as post body" ) @Valid @RequestBody(required = false) OuterComposite body) { - return delegate.fakeOuterCompositeSerialize(body); - } - - /** - * POST /fake/outer/number - * Test serialization of outer number types - * - * @param body Input number as post body (optional) - * @return Output number (status code 200) - * @see FakeApi#fakeOuterNumberSerialize - */ - public ResponseEntity fakeOuterNumberSerialize(@ApiParam(value = "Input number as post body" ) @Valid @RequestBody(required = false) BigDecimal body) { - return delegate.fakeOuterNumberSerialize(body); - } - - /** - * POST /fake/outer/string - * Test serialization of outer string types - * - * @param body Input string as post body (optional) - * @return Output string (status code 200) - * @see FakeApi#fakeOuterStringSerialize - */ - public ResponseEntity fakeOuterStringSerialize(@ApiParam(value = "Input string as post body" ) @Valid @RequestBody(required = false) String body) { - return delegate.fakeOuterStringSerialize(body); - } - - /** - * PUT /fake/body-with-file-schema - * For this test, the body for this request much reference a schema named `File`. - * - * @param body (required) - * @return Success (status code 200) - * @see FakeApi#testBodyWithFileSchema - */ - public ResponseEntity testBodyWithFileSchema(@ApiParam(value = "" ,required=true ) @Valid @RequestBody FileSchemaTestClass body) { - return delegate.testBodyWithFileSchema(body); - } - - /** - * PUT /fake/body-with-query-params - * - * @param query (required) - * @param body (required) - * @return Success (status code 200) - * @see FakeApi#testBodyWithQueryParams - */ - public ResponseEntity testBodyWithQueryParams(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "query", required = true) String query,@ApiParam(value = "" ,required=true ) @Valid @RequestBody User body) { - return delegate.testBodyWithQueryParams(query, body); - } - - /** - * PATCH /fake : To test \"client\" model - * To test \"client\" model - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see FakeApi#testClientModel - */ - public ResponseEntity testClientModel(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - return delegate.testClientModel(body); - } - - /** - * POST /fake : Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - * - * @param number None (required) - * @param _double None (required) - * @param patternWithoutDelimiter None (required) - * @param _byte None (required) - * @param integer None (optional) - * @param int32 None (optional) - * @param int64 None (optional) - * @param _float None (optional) - * @param string None (optional) - * @param binary None (optional) - * @param date None (optional) - * @param dateTime None (optional) - * @param password None (optional) - * @param paramCallback None (optional) - * @return Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see FakeApi#testEndpointParameters - */ - public ResponseEntity testEndpointParameters(@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "number", required = true) BigDecimal number,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "double", required = true) Double _double,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "pattern_without_delimiter", required = true) String patternWithoutDelimiter,@ApiParam(value = "None", required=true) @Valid @RequestPart(value = "byte", required = true) byte[] _byte,@ApiParam(value = "None") @Valid @RequestPart(value = "integer", required = false) Integer integer,@ApiParam(value = "None") @Valid @RequestPart(value = "int32", required = false) Integer int32,@ApiParam(value = "None") @Valid @RequestPart(value = "int64", required = false) Long int64,@ApiParam(value = "None") @Valid @RequestPart(value = "float", required = false) Float _float,@ApiParam(value = "None") @Valid @RequestPart(value = "string", required = false) String string,@ApiParam(value = "None") @Valid @RequestPart(value = "binary", required = false) MultipartFile binary,@ApiParam(value = "None") @Valid @RequestPart(value = "date", required = false) LocalDate date,@ApiParam(value = "None") @Valid @RequestPart(value = "dateTime", required = false) OffsetDateTime dateTime,@ApiParam(value = "None") @Valid @RequestPart(value = "password", required = false) String password,@ApiParam(value = "None") @Valid @RequestPart(value = "callback", required = false) String paramCallback) { - return delegate.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); - } - - /** - * GET /fake : To test enum parameters - * To test enum parameters - * - * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<String>()) - * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<String>()) - * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) - * @param enumQueryInteger Query parameter enum test (double) (optional) - * @param enumQueryDouble Query parameter enum test (double) (optional) - * @param enumFormStringArray Form parameter enum test (string array) (optional, default to $) - * @param enumFormString Form parameter enum test (string) (optional, default to -efg) - * @return Invalid request (status code 400) - * or Not found (status code 404) - * @see FakeApi#testEnumParameters - */ - public ResponseEntity testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $") @RequestHeader(value="enum_header_string_array", required=false) List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @RequestHeader(value="enum_header_string", required=false) String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)", allowableValues = ">, $") @Valid @RequestParam(value = "enum_query_string_array", required = false) List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues = "_abc, -efg, (xyz)", defaultValue = "-efg") @Valid @RequestParam(value = "enum_query_string", required = false, defaultValue="-efg") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1, -2") @Valid @RequestParam(value = "enum_query_integer", required = false) Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues = "1.1, -1.2") @Valid @RequestParam(value = "enum_query_double", required = false) Double enumQueryDouble,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $") @Valid @RequestPart(value = "enum_form_string_array", required = false) List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @Valid @RequestPart(value = "enum_form_string", required = false) String enumFormString) { - return delegate.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); - } - - /** - * DELETE /fake : Fake endpoint to test group parameters (optional) - * Fake endpoint to test group parameters (optional) - * - * @param requiredStringGroup Required String in group parameters (required) - * @param requiredBooleanGroup Required Boolean in group parameters (required) - * @param requiredInt64Group Required Integer in group parameters (required) - * @param stringGroup String in group parameters (optional) - * @param booleanGroup Boolean in group parameters (optional) - * @param int64Group Integer in group parameters (optional) - * @return Someting wrong (status code 400) - * @see FakeApi#testGroupParameters - */ - public ResponseEntity testGroupParameters(@NotNull @ApiParam(value = "Required String in group parameters", required = true) @Valid @RequestParam(value = "required_string_group", required = true) Integer requiredStringGroup,@ApiParam(value = "Required Boolean in group parameters" ,required=true) @RequestHeader(value="required_boolean_group", required=true) Boolean requiredBooleanGroup,@NotNull @ApiParam(value = "Required Integer in group parameters", required = true) @Valid @RequestParam(value = "required_int64_group", required = true) Long requiredInt64Group,@ApiParam(value = "String in group parameters") @Valid @RequestParam(value = "string_group", required = false) Integer stringGroup,@ApiParam(value = "Boolean in group parameters" ) @RequestHeader(value="boolean_group", required=false) Boolean booleanGroup,@ApiParam(value = "Integer in group parameters") @Valid @RequestParam(value = "int64_group", required = false) Long int64Group) { - return delegate.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); - } - - /** - * POST /fake/inline-additionalProperties : test inline additionalProperties - * - * @param param request body (required) - * @return successful operation (status code 200) - * @see FakeApi#testInlineAdditionalProperties - */ - public ResponseEntity testInlineAdditionalProperties(@ApiParam(value = "request body" ,required=true ) @Valid @RequestBody Map param) { - return delegate.testInlineAdditionalProperties(param); - } - - /** - * GET /fake/jsonFormData : test json serialization of form data - * - * @param param field1 (required) - * @param param2 field2 (required) - * @return successful operation (status code 200) - * @see FakeApi#testJsonFormData - */ - public ResponseEntity testJsonFormData(@ApiParam(value = "field1", required=true) @Valid @RequestPart(value = "param", required = true) String param,@ApiParam(value = "field2", required=true) @Valid @RequestPart(value = "param2", required = true) String param2) { - return delegate.testJsonFormData(param, param2); - } - - /** - * PUT /fake/test-query-paramters - * To test the collection format in query parameters - * - * @param pipe (required) - * @param ioutil (required) - * @param http (required) - * @param url (required) - * @param context (required) - * @return Success (status code 200) - * @see FakeApi#testQueryParameterCollectionFormat - */ - public ResponseEntity testQueryParameterCollectionFormat(@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "pipe", required = true) List pipe,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "ioutil", required = true) List ioutil,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "http", required = true) List http,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "url", required = true) List url,@NotNull @ApiParam(value = "", required = true) @Valid @RequestParam(value = "context", required = true) List context) { - return delegate.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + this.delegate = Optional.ofNullable(delegate).orElse(new FakeApiDelegate() {}); } - /** - * POST /fake/{petId}/uploadImageWithRequiredFile : uploads an image (required) - * - * @param petId ID of pet to update (required) - * @param requiredFile file to upload (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @return successful operation (status code 200) - * @see FakeApi#uploadFileWithRequiredFile - */ - public ResponseEntity uploadFileWithRequiredFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "requiredFile", required = true) MultipartFile requiredFile,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata) { - return delegate.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + @Override + public FakeApiDelegate getDelegate() { + return delegate; } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiDelegate.java index c28f5b8e99fb..48f9c6a1ae63 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApiDelegate.java @@ -3,20 +3,24 @@ import java.math.BigDecimal; import org.openapitools.model.Client; import org.openapitools.model.FileSchemaTestClass; -import org.threeten.bp.LocalDate; +import java.time.LocalDate; import java.util.Map; import org.openapitools.model.ModelApiResponse; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; import org.openapitools.model.OuterComposite; import org.springframework.core.io.Resource; import org.openapitools.model.User; import org.openapitools.model.XmlItem; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; +import java.util.Optional; /** * A delegate to be called by the {@link FakeApiController}}. @@ -25,6 +29,10 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public interface FakeApiDelegate { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /fake/create_xml_item : creates an XmlItem * this route creates an XmlItem @@ -33,7 +41,10 @@ public interface FakeApiDelegate { * @return successful operation (status code 200) * @see FakeApi#createXmlItem */ - ResponseEntity createXmlItem(XmlItem xmlItem); + default ResponseEntity createXmlItem(XmlItem xmlItem) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /fake/outer/boolean @@ -43,7 +54,10 @@ public interface FakeApiDelegate { * @return Output boolean (status code 200) * @see FakeApi#fakeOuterBooleanSerialize */ - ResponseEntity fakeOuterBooleanSerialize(Boolean body); + default ResponseEntity fakeOuterBooleanSerialize(Boolean body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /fake/outer/composite @@ -53,7 +67,19 @@ public interface FakeApiDelegate { * @return Output composite (status code 200) * @see FakeApi#fakeOuterCompositeSerialize */ - ResponseEntity fakeOuterCompositeSerialize(OuterComposite body); + default ResponseEntity fakeOuterCompositeSerialize(OuterComposite body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("*/*"))) { + String exampleString = "{ \"my_string\" : \"my_string\", \"my_number\" : 0.8008281904610115, \"my_boolean\" : true }"; + ApiUtil.setExampleResponse(request, "*/*", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /fake/outer/number @@ -63,7 +89,10 @@ public interface FakeApiDelegate { * @return Output number (status code 200) * @see FakeApi#fakeOuterNumberSerialize */ - ResponseEntity fakeOuterNumberSerialize(BigDecimal body); + default ResponseEntity fakeOuterNumberSerialize(BigDecimal body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /fake/outer/string @@ -73,7 +102,10 @@ public interface FakeApiDelegate { * @return Output string (status code 200) * @see FakeApi#fakeOuterStringSerialize */ - ResponseEntity fakeOuterStringSerialize(String body); + default ResponseEntity fakeOuterStringSerialize(String body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * PUT /fake/body-with-file-schema @@ -83,7 +115,10 @@ public interface FakeApiDelegate { * @return Success (status code 200) * @see FakeApi#testBodyWithFileSchema */ - ResponseEntity testBodyWithFileSchema(FileSchemaTestClass body); + default ResponseEntity testBodyWithFileSchema(FileSchemaTestClass body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * PUT /fake/body-with-query-params @@ -93,8 +128,11 @@ public interface FakeApiDelegate { * @return Success (status code 200) * @see FakeApi#testBodyWithQueryParams */ - ResponseEntity testBodyWithQueryParams(String query, - User body); + default ResponseEntity testBodyWithQueryParams(String query, + User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * PATCH /fake : To test \"client\" model @@ -104,7 +142,19 @@ ResponseEntity testBodyWithQueryParams(String query, * @return successful operation (status code 200) * @see FakeApi#testClientModel */ - ResponseEntity testClientModel(Client body); + default ResponseEntity testClientModel(Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /fake : Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -128,7 +178,7 @@ ResponseEntity testBodyWithQueryParams(String query, * or User not found (status code 404) * @see FakeApi#testEndpointParameters */ - ResponseEntity testEndpointParameters(BigDecimal number, + default ResponseEntity testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, @@ -141,15 +191,18 @@ ResponseEntity testEndpointParameters(BigDecimal number, LocalDate date, OffsetDateTime dateTime, String password, - String paramCallback); + String paramCallback) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /fake : To test enum parameters * To test enum parameters * - * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumHeaderStringArray Header parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) - * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<String>()) + * @param enumQueryStringArray Query parameter enum test (string array) (optional, default to new ArrayList<>()) * @param enumQueryString Query parameter enum test (string) (optional, default to -efg) * @param enumQueryInteger Query parameter enum test (double) (optional) * @param enumQueryDouble Query parameter enum test (double) (optional) @@ -159,14 +212,17 @@ ResponseEntity testEndpointParameters(BigDecimal number, * or Not found (status code 404) * @see FakeApi#testEnumParameters */ - ResponseEntity testEnumParameters(List enumHeaderStringArray, + default ResponseEntity testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, - String enumFormString); + String enumFormString) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * DELETE /fake : Fake endpoint to test group parameters (optional) @@ -181,12 +237,15 @@ ResponseEntity testEnumParameters(List enumHeaderStringArray, * @return Someting wrong (status code 400) * @see FakeApi#testGroupParameters */ - ResponseEntity testGroupParameters(Integer requiredStringGroup, + default ResponseEntity testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, - Long int64Group); + Long int64Group) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /fake/inline-additionalProperties : test inline additionalProperties @@ -195,7 +254,10 @@ ResponseEntity testGroupParameters(Integer requiredStringGroup, * @return successful operation (status code 200) * @see FakeApi#testInlineAdditionalProperties */ - ResponseEntity testInlineAdditionalProperties(Map param); + default ResponseEntity testInlineAdditionalProperties(Map param) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /fake/jsonFormData : test json serialization of form data @@ -205,8 +267,11 @@ ResponseEntity testGroupParameters(Integer requiredStringGroup, * @return successful operation (status code 200) * @see FakeApi#testJsonFormData */ - ResponseEntity testJsonFormData(String param, - String param2); + default ResponseEntity testJsonFormData(String param, + String param2) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * PUT /fake/test-query-paramters @@ -220,11 +285,14 @@ ResponseEntity testJsonFormData(String param, * @return Success (status code 200) * @see FakeApi#testQueryParameterCollectionFormat */ - ResponseEntity testQueryParameterCollectionFormat(List pipe, + default ResponseEntity testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, - List context); + List context) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /fake/{petId}/uploadImageWithRequiredFile : uploads an image (required) @@ -235,8 +303,20 @@ ResponseEntity testQueryParameterCollectionFormat(List pipe, * @return successful operation (status code 200) * @see FakeApi#uploadFileWithRequiredFile */ - ResponseEntity uploadFileWithRequiredFile(Long petId, + default ResponseEntity uploadFileWithRequiredFile(Long petId, MultipartFile requiredFile, - String additionalMetadata); + String additionalMetadata) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 723fc9f62ac5..6b02c884009d 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -21,6 +21,10 @@ @Api(value = "fake_classname_test", description = "the fake_classname_test API") public interface FakeClassnameTestApi { + default FakeClassnameTestApiDelegate getDelegate() { + return new FakeClassnameTestApiDelegate() {}; + } + /** * PATCH /fake_classname_test : To test class name in snake case * To test class name in snake case @@ -38,6 +42,8 @@ public interface FakeClassnameTestApi { produces = { "application/json" }, consumes = { "application/json" } ) - ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body); + default ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { + return getDelegate().testClassname(body); + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java index 5c14bb5bed37..58497641e4c5 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiController.java @@ -1,24 +1,8 @@ package org.openapitools.api; -import org.openapitools.model.Client; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -27,19 +11,12 @@ public class FakeClassnameTestApiController implements FakeClassnameTestApi { private final FakeClassnameTestApiDelegate delegate; public FakeClassnameTestApiController(@org.springframework.beans.factory.annotation.Autowired(required = false) FakeClassnameTestApiDelegate delegate) { - this.delegate = delegate; + this.delegate = Optional.ofNullable(delegate).orElse(new FakeClassnameTestApiDelegate() {}); } - /** - * PATCH /fake_classname_test : To test class name in snake case - * To test class name in snake case - * - * @param body client model (required) - * @return successful operation (status code 200) - * @see FakeClassnameTestApi#testClassname - */ - public ResponseEntity testClassname(@ApiParam(value = "client model" ,required=true ) @Valid @RequestBody Client body) { - return delegate.testClassname(body); + @Override + public FakeClassnameTestApiDelegate getDelegate() { + return delegate; } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java index 20d9b798c627..c71fe13d195a 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java @@ -2,11 +2,15 @@ import org.openapitools.model.Client; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; +import java.util.Optional; /** * A delegate to be called by the {@link FakeClassnameTestApiController}}. @@ -15,6 +19,10 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public interface FakeClassnameTestApiDelegate { + default Optional getRequest() { + return Optional.empty(); + } + /** * PATCH /fake_classname_test : To test class name in snake case * To test class name in snake case @@ -23,6 +31,18 @@ public interface FakeClassnameTestApiDelegate { * @return successful operation (status code 200) * @see FakeClassnameTestApi#testClassname */ - ResponseEntity testClassname(Client body); + default ResponseEntity testClassname(Client body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"client\" : \"client\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java index 7ab2f6e9d5f7..ffdbde323f1e 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java @@ -24,6 +24,10 @@ @Api(value = "pet", description = "the pet API") public interface PetApi { + default PetApiDelegate getDelegate() { + return new PetApiDelegate() {}; + } + /** * POST /pet : Add a new pet to the store * @@ -44,7 +48,9 @@ public interface PetApi { value = "/pet", consumes = { "application/json", "application/xml" } ) - ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); + default ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return getDelegate().addPet(body); + } /** @@ -67,7 +73,9 @@ public interface PetApi { @DeleteMapping( value = "/pet/{petId}" ) - ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey); + default ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { + return getDelegate().deletePet(petId, apiKey); + } /** @@ -91,7 +99,9 @@ public interface PetApi { value = "/pet/findByStatus", produces = { "application/xml", "application/json" } ) - ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status); + default ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { + return getDelegate().findPetsByStatus(status); + } /** @@ -116,7 +126,9 @@ public interface PetApi { value = "/pet/findByTags", produces = { "application/xml", "application/json" } ) - ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags); + default ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags) { + return getDelegate().findPetsByTags(tags); + } /** @@ -139,7 +151,9 @@ public interface PetApi { value = "/pet/{petId}", produces = { "application/xml", "application/json" } ) - ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId); + default ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { + return getDelegate().getPetById(petId); + } /** @@ -166,7 +180,9 @@ public interface PetApi { value = "/pet", consumes = { "application/json", "application/xml" } ) - ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body); + default ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { + return getDelegate().updatePet(body); + } /** @@ -189,7 +205,9 @@ public interface PetApi { value = "/pet/{petId}", consumes = { "application/x-www-form-urlencoded" } ) - ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status); + default ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status) { + return getDelegate().updatePetWithForm(petId, name, status); + } /** @@ -213,6 +231,8 @@ public interface PetApi { produces = { "application/json" }, consumes = { "multipart/form-data" } ) - ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file); + default ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) { + return getDelegate().uploadFile(petId, additionalMetadata, file); + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java index 4a8a378932dc..5fa088c6f10b 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiController.java @@ -1,27 +1,8 @@ package org.openapitools.api; -import org.openapitools.model.ModelApiResponse; -import org.openapitools.model.Pet; -import org.springframework.core.io.Resource; -import java.util.Set; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -30,113 +11,12 @@ public class PetApiController implements PetApi { private final PetApiDelegate delegate; public PetApiController(@org.springframework.beans.factory.annotation.Autowired(required = false) PetApiDelegate delegate) { - this.delegate = delegate; - } - - /** - * POST /pet : Add a new pet to the store - * - * @param body Pet object that needs to be added to the store (required) - * @return successful operation (status code 200) - * or Invalid input (status code 405) - * @see PetApi#addPet - */ - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { - return delegate.addPet(body); - } - - /** - * DELETE /pet/{petId} : Deletes a pet - * - * @param petId Pet id to delete (required) - * @param apiKey (optional) - * @return successful operation (status code 200) - * or Invalid pet value (status code 400) - * @see PetApi#deletePet - */ - public ResponseEntity deletePet(@ApiParam(value = "Pet id to delete",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "" ) @RequestHeader(value="api_key", required=false) String apiKey) { - return delegate.deletePet(petId, apiKey); - } - - /** - * GET /pet/findByStatus : Finds Pets by status - * Multiple status values can be provided with comma separated strings - * - * @param status Status values that need to be considered for filter (required) - * @return successful operation (status code 200) - * or Invalid status value (status code 400) - * @see PetApi#findPetsByStatus - */ - public ResponseEntity> findPetsByStatus(@NotNull @ApiParam(value = "Status values that need to be considered for filter", required = true, allowableValues = "available, pending, sold") @Valid @RequestParam(value = "status", required = true) List status) { - return delegate.findPetsByStatus(status); - } - - /** - * GET /pet/findByTags : Finds Pets by tags - * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. - * - * @param tags Tags to filter by (required) - * @return successful operation (status code 200) - * or Invalid tag value (status code 400) - * @deprecated - * @see PetApi#findPetsByTags - */ - public ResponseEntity> findPetsByTags(@NotNull @ApiParam(value = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) Set tags) { - return delegate.findPetsByTags(tags); - } - - /** - * GET /pet/{petId} : Find pet by ID - * Returns a single pet - * - * @param petId ID of pet to return (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Pet not found (status code 404) - * @see PetApi#getPetById - */ - public ResponseEntity getPetById(@ApiParam(value = "ID of pet to return",required=true) @PathVariable("petId") Long petId) { - return delegate.getPetById(petId); - } - - /** - * PUT /pet : Update an existing pet - * - * @param body Pet object that needs to be added to the store (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Pet not found (status code 404) - * or Validation exception (status code 405) - * @see PetApi#updatePet - */ - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @Valid @RequestBody Pet body) { - return delegate.updatePet(body); - } - - /** - * POST /pet/{petId} : Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated (required) - * @param name Updated name of the pet (optional) - * @param status Updated status of the pet (optional) - * @return Invalid input (status code 405) - * @see PetApi#updatePetWithForm - */ - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Updated name of the pet") @Valid @RequestPart(value = "name", required = false) String name,@ApiParam(value = "Updated status of the pet") @Valid @RequestPart(value = "status", required = false) String status) { - return delegate.updatePetWithForm(petId, name, status); + this.delegate = Optional.ofNullable(delegate).orElse(new PetApiDelegate() {}); } - /** - * POST /pet/{petId}/uploadImage : uploads an image - * - * @param petId ID of pet to update (required) - * @param additionalMetadata Additional data to pass to server (optional) - * @param file file to upload (optional) - * @return successful operation (status code 200) - * @see PetApi#uploadFile - */ - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true) @PathVariable("petId") Long petId,@ApiParam(value = "Additional data to pass to server") @Valid @RequestPart(value = "additionalMetadata", required = false) String additionalMetadata,@ApiParam(value = "file to upload") @Valid @RequestPart(value = "file", required = false) MultipartFile file) { - return delegate.uploadFile(petId, additionalMetadata, file); + @Override + public PetApiDelegate getDelegate() { + return delegate; } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiDelegate.java index 426aeb269488..5a70de5ef3e6 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApiDelegate.java @@ -5,11 +5,15 @@ import org.springframework.core.io.Resource; import java.util.Set; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; +import java.util.Optional; /** * A delegate to be called by the {@link PetApiController}}. @@ -18,6 +22,10 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public interface PetApiDelegate { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /pet : Add a new pet to the store * @@ -26,7 +34,10 @@ public interface PetApiDelegate { * or Invalid input (status code 405) * @see PetApi#addPet */ - ResponseEntity addPet(Pet body); + default ResponseEntity addPet(Pet body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * DELETE /pet/{petId} : Deletes a pet @@ -37,8 +48,11 @@ public interface PetApiDelegate { * or Invalid pet value (status code 400) * @see PetApi#deletePet */ - ResponseEntity deletePet(Long petId, - String apiKey); + default ResponseEntity deletePet(Long petId, + String apiKey) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /pet/findByStatus : Finds Pets by status @@ -49,7 +63,24 @@ ResponseEntity deletePet(Long petId, * or Invalid status value (status code 400) * @see PetApi#findPetsByStatus */ - ResponseEntity> findPetsByStatus(List status); + default ResponseEntity> findPetsByStatus(List status) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /pet/findByTags : Finds Pets by tags @@ -61,7 +92,24 @@ ResponseEntity deletePet(Long petId, * @deprecated * @see PetApi#findPetsByTags */ - ResponseEntity> findPetsByTags(Set tags); + default ResponseEntity> findPetsByTags(Set tags) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /pet/{petId} : Find pet by ID @@ -73,7 +121,24 @@ ResponseEntity deletePet(Long petId, * or Pet not found (status code 404) * @see PetApi#getPetById */ - ResponseEntity getPetById(Long petId); + default ResponseEntity getPetById(Long petId) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"photoUrls\" : [ \"photoUrls\", \"photoUrls\" ], \"name\" : \"doggie\", \"id\" : 0, \"category\" : { \"name\" : \"default-name\", \"id\" : 6 }, \"tags\" : [ { \"name\" : \"name\", \"id\" : 1 }, { \"name\" : \"name\", \"id\" : 1 } ], \"status\" : \"available\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 doggie aeiou aeiou "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * PUT /pet : Update an existing pet @@ -85,7 +150,10 @@ ResponseEntity deletePet(Long petId, * or Validation exception (status code 405) * @see PetApi#updatePet */ - ResponseEntity updatePet(Pet body); + default ResponseEntity updatePet(Pet body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /pet/{petId} : Updates a pet in the store with form data @@ -96,9 +164,12 @@ ResponseEntity deletePet(Long petId, * @return Invalid input (status code 405) * @see PetApi#updatePetWithForm */ - ResponseEntity updatePetWithForm(Long petId, + default ResponseEntity updatePetWithForm(Long petId, String name, - String status); + String status) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /pet/{petId}/uploadImage : uploads an image @@ -109,8 +180,20 @@ ResponseEntity updatePetWithForm(Long petId, * @return successful operation (status code 200) * @see PetApi#uploadFile */ - ResponseEntity uploadFile(Long petId, + default ResponseEntity uploadFile(Long petId, String additionalMetadata, - MultipartFile file); + MultipartFile file) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"code\" : 0, \"type\" : \"type\", \"message\" : \"message\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java index 0128cb2d54b8..96c812bb6972 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java @@ -22,6 +22,10 @@ @Api(value = "store", description = "the store API") public interface StoreApi { + default StoreApiDelegate getDelegate() { + return new StoreApiDelegate() {}; + } + /** * DELETE /store/order/{order_id} : Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -37,7 +41,9 @@ public interface StoreApi { @DeleteMapping( value = "/store/order/{order_id}" ) - ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId); + default ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { + return getDelegate().deleteOrder(orderId); + } /** @@ -55,7 +61,9 @@ public interface StoreApi { value = "/store/inventory", produces = { "application/json" } ) - ResponseEntity> getInventory(); + default ResponseEntity> getInventory() { + return getDelegate().getInventory(); + } /** @@ -76,7 +84,9 @@ public interface StoreApi { value = "/store/order/{order_id}", produces = { "application/xml", "application/json" } ) - ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId); + default ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { + return getDelegate().getOrderById(orderId); + } /** @@ -94,6 +104,8 @@ public interface StoreApi { value = "/store/order", produces = { "application/xml", "application/json" } ) - ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body); + default ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { + return getDelegate().placeOrder(body); + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java index ad6c539471b0..9e08c646ae92 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiController.java @@ -1,25 +1,8 @@ package org.openapitools.api; -import java.util.Map; -import org.openapitools.model.Order; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -28,57 +11,12 @@ public class StoreApiController implements StoreApi { private final StoreApiDelegate delegate; public StoreApiController(@org.springframework.beans.factory.annotation.Autowired(required = false) StoreApiDelegate delegate) { - this.delegate = delegate; - } - - /** - * DELETE /store/order/{order_id} : Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @param orderId ID of the order that needs to be deleted (required) - * @return Invalid ID supplied (status code 400) - * or Order not found (status code 404) - * @see StoreApi#deleteOrder - */ - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true) @PathVariable("order_id") String orderId) { - return delegate.deleteOrder(orderId); - } - - /** - * GET /store/inventory : Returns pet inventories by status - * Returns a map of status codes to quantities - * - * @return successful operation (status code 200) - * @see StoreApi#getInventory - */ - public ResponseEntity> getInventory() { - return delegate.getInventory(); - } - - /** - * GET /store/order/{order_id} : Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @param orderId ID of pet that needs to be fetched (required) - * @return successful operation (status code 200) - * or Invalid ID supplied (status code 400) - * or Order not found (status code 404) - * @see StoreApi#getOrderById - */ - public ResponseEntity getOrderById(@Min(1L) @Max(5L) @ApiParam(value = "ID of pet that needs to be fetched",required=true) @PathVariable("order_id") Long orderId) { - return delegate.getOrderById(orderId); + this.delegate = Optional.ofNullable(delegate).orElse(new StoreApiDelegate() {}); } - /** - * POST /store/order : Place an order for a pet - * - * @param body order placed for purchasing the pet (required) - * @return successful operation (status code 200) - * or Invalid Order (status code 400) - * @see StoreApi#placeOrder - */ - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @Valid @RequestBody Order body) { - return delegate.placeOrder(body); + @Override + public StoreApiDelegate getDelegate() { + return delegate; } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiDelegate.java index a7bfc60e1289..5091e7e1f2cc 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApiDelegate.java @@ -3,11 +3,15 @@ import java.util.Map; import org.openapitools.model.Order; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; +import java.util.Optional; /** * A delegate to be called by the {@link StoreApiController}}. @@ -16,6 +20,10 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public interface StoreApiDelegate { + default Optional getRequest() { + return Optional.empty(); + } + /** * DELETE /store/order/{order_id} : Delete purchase order by ID * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -25,7 +33,10 @@ public interface StoreApiDelegate { * or Order not found (status code 404) * @see StoreApi#deleteOrder */ - ResponseEntity deleteOrder(String orderId); + default ResponseEntity deleteOrder(String orderId) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /store/inventory : Returns pet inventories by status @@ -34,7 +45,10 @@ public interface StoreApiDelegate { * @return successful operation (status code 200) * @see StoreApi#getInventory */ - ResponseEntity> getInventory(); + default ResponseEntity> getInventory() { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /store/order/{order_id} : Find purchase order by ID @@ -46,7 +60,24 @@ public interface StoreApiDelegate { * or Order not found (status code 404) * @see StoreApi#getOrderById */ - ResponseEntity getOrderById(Long orderId); + default ResponseEntity getOrderById(Long orderId) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /store/order : Place an order for a pet @@ -56,6 +87,23 @@ public interface StoreApiDelegate { * or Invalid Order (status code 400) * @see StoreApi#placeOrder */ - ResponseEntity placeOrder(Order body); + default ResponseEntity placeOrder(Order body) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"petId\" : 6, \"quantity\" : 1, \"id\" : 0, \"shipDate\" : \"2000-01-23T04:56:07.000+00:00\", \"complete\" : false, \"status\" : \"placed\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 123456789 123 2000-01-23T04:56:07.000Z aeiou true "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java index e1d4245a6b15..f572889cda63 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java @@ -22,6 +22,10 @@ @Api(value = "user", description = "the user API") public interface UserApi { + default UserApiDelegate getDelegate() { + return new UserApiDelegate() {}; + } + /** * POST /user : Create user * This can only be done by the logged in user. @@ -35,7 +39,9 @@ public interface UserApi { @PostMapping( value = "/user" ) - ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { + return getDelegate().createUser(body); + } /** @@ -50,7 +56,9 @@ public interface UserApi { @PostMapping( value = "/user/createWithArray" ) - ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); + default ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return getDelegate().createUsersWithArrayInput(body); + } /** @@ -65,7 +73,9 @@ public interface UserApi { @PostMapping( value = "/user/createWithList" ) - ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body); + default ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { + return getDelegate().createUsersWithListInput(body); + } /** @@ -83,7 +93,9 @@ public interface UserApi { @DeleteMapping( value = "/user/{username}" ) - ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username); + default ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { + return getDelegate().deleteUser(username); + } /** @@ -103,7 +115,9 @@ public interface UserApi { value = "/user/{username}", produces = { "application/xml", "application/json" } ) - ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username); + default ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username) { + return getDelegate().getUserByName(username); + } /** @@ -122,7 +136,9 @@ public interface UserApi { value = "/user/login", produces = { "application/xml", "application/json" } ) - ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password); + default ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { + return getDelegate().loginUser(username, password); + } /** @@ -136,7 +152,9 @@ public interface UserApi { @GetMapping( value = "/user/logout" ) - ResponseEntity logoutUser(); + default ResponseEntity logoutUser() { + return getDelegate().logoutUser(); + } /** @@ -155,6 +173,8 @@ public interface UserApi { @PutMapping( value = "/user/{username}" ) - ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body); + default ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { + return getDelegate().updateUser(username, body); + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java index 4ee524e3a04d..bc2d33598fd9 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiController.java @@ -1,25 +1,8 @@ package org.openapitools.api; -import java.util.List; -import org.openapitools.model.User; -import io.swagger.annotations.*; -import org.springframework.http.HttpStatus; -import org.springframework.http.MediaType; -import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.CookieValue; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RequestPart; -import org.springframework.web.multipart.MultipartFile; - -import javax.validation.constraints.*; -import javax.validation.Valid; -import java.util.List; -import java.util.Map; +import java.util.Optional; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") @Controller @RequestMapping("${openapi.openAPIPetstore.base-path:/v2}") @@ -28,104 +11,12 @@ public class UserApiController implements UserApi { private final UserApiDelegate delegate; public UserApiController(@org.springframework.beans.factory.annotation.Autowired(required = false) UserApiDelegate delegate) { - this.delegate = delegate; - } - - /** - * POST /user : Create user - * This can only be done by the logged in user. - * - * @param body Created user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUser - */ - public ResponseEntity createUser(@ApiParam(value = "Created user object" ,required=true ) @Valid @RequestBody User body) { - return delegate.createUser(body); - } - - /** - * POST /user/createWithArray : Creates list of users with given input array - * - * @param body List of user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUsersWithArrayInput - */ - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { - return delegate.createUsersWithArrayInput(body); - } - - /** - * POST /user/createWithList : Creates list of users with given input array - * - * @param body List of user object (required) - * @return successful operation (status code 200) - * @see UserApi#createUsersWithListInput - */ - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true ) @Valid @RequestBody List body) { - return delegate.createUsersWithListInput(body); - } - - /** - * DELETE /user/{username} : Delete user - * This can only be done by the logged in user. - * - * @param username The name that needs to be deleted (required) - * @return Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#deleteUser - */ - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true) @PathVariable("username") String username) { - return delegate.deleteUser(username); - } - - /** - * GET /user/{username} : Get user by user name - * - * @param username The name that needs to be fetched. Use user1 for testing. (required) - * @return successful operation (status code 200) - * or Invalid username supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#getUserByName - */ - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true) @PathVariable("username") String username) { - return delegate.getUserByName(username); - } - - /** - * GET /user/login : Logs user into the system - * - * @param username The user name for login (required) - * @param password The password for login in clear text (required) - * @return successful operation (status code 200) - * or Invalid username/password supplied (status code 400) - * @see UserApi#loginUser - */ - public ResponseEntity loginUser(@NotNull @ApiParam(value = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) String username,@NotNull @ApiParam(value = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) String password) { - return delegate.loginUser(username, password); - } - - /** - * GET /user/logout : Logs out current logged in user session - * - * @return successful operation (status code 200) - * @see UserApi#logoutUser - */ - public ResponseEntity logoutUser() { - return delegate.logoutUser(); + this.delegate = Optional.ofNullable(delegate).orElse(new UserApiDelegate() {}); } - /** - * PUT /user/{username} : Updated user - * This can only be done by the logged in user. - * - * @param username name that need to be deleted (required) - * @param body Updated user object (required) - * @return Invalid user supplied (status code 400) - * or User not found (status code 404) - * @see UserApi#updateUser - */ - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true) @PathVariable("username") String username,@ApiParam(value = "Updated user object" ,required=true ) @Valid @RequestBody User body) { - return delegate.updateUser(username, body); + @Override + public UserApiDelegate getDelegate() { + return delegate; } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java index 81c3ecc25887..78da7c8510bc 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java @@ -3,11 +3,15 @@ import java.util.List; import org.openapitools.model.User; import io.swagger.annotations.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; +import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.multipart.MultipartFile; import java.util.List; import java.util.Map; +import java.util.Optional; /** * A delegate to be called by the {@link UserApiController}}. @@ -16,6 +20,10 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public interface UserApiDelegate { + default Optional getRequest() { + return Optional.empty(); + } + /** * POST /user : Create user * This can only be done by the logged in user. @@ -24,7 +32,10 @@ public interface UserApiDelegate { * @return successful operation (status code 200) * @see UserApi#createUser */ - ResponseEntity createUser(User body); + default ResponseEntity createUser(User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /user/createWithArray : Creates list of users with given input array @@ -33,7 +44,10 @@ public interface UserApiDelegate { * @return successful operation (status code 200) * @see UserApi#createUsersWithArrayInput */ - ResponseEntity createUsersWithArrayInput(List body); + default ResponseEntity createUsersWithArrayInput(List body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * POST /user/createWithList : Creates list of users with given input array @@ -42,7 +56,10 @@ public interface UserApiDelegate { * @return successful operation (status code 200) * @see UserApi#createUsersWithListInput */ - ResponseEntity createUsersWithListInput(List body); + default ResponseEntity createUsersWithListInput(List body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * DELETE /user/{username} : Delete user @@ -53,7 +70,10 @@ public interface UserApiDelegate { * or User not found (status code 404) * @see UserApi#deleteUser */ - ResponseEntity deleteUser(String username); + default ResponseEntity deleteUser(String username) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /user/{username} : Get user by user name @@ -64,7 +84,24 @@ public interface UserApiDelegate { * or User not found (status code 404) * @see UserApi#getUserByName */ - ResponseEntity getUserByName(String username); + default ResponseEntity getUserByName(String username) { + getRequest().ifPresent(request -> { + for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { + if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { + String exampleString = "{ \"firstName\" : \"firstName\", \"lastName\" : \"lastName\", \"password\" : \"password\", \"userStatus\" : 6, \"phone\" : \"phone\", \"id\" : 0, \"email\" : \"email\", \"username\" : \"username\" }"; + ApiUtil.setExampleResponse(request, "application/json", exampleString); + break; + } + if (mediaType.isCompatibleWith(MediaType.valueOf("application/xml"))) { + String exampleString = " 123456789 aeiou aeiou aeiou aeiou aeiou aeiou 123 "; + ApiUtil.setExampleResponse(request, "application/xml", exampleString); + break; + } + } + }); + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /user/login : Logs user into the system @@ -75,8 +112,11 @@ public interface UserApiDelegate { * or Invalid username/password supplied (status code 400) * @see UserApi#loginUser */ - ResponseEntity loginUser(String username, - String password); + default ResponseEntity loginUser(String username, + String password) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * GET /user/logout : Logs out current logged in user session @@ -84,7 +124,10 @@ ResponseEntity loginUser(String username, * @return successful operation (status code 200) * @see UserApi#logoutUser */ - ResponseEntity logoutUser(); + default ResponseEntity logoutUser() { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } /** * PUT /user/{username} : Updated user @@ -96,7 +139,10 @@ ResponseEntity loginUser(String username, * or User not found (status code 404) * @see UserApi#updateUser */ - ResponseEntity updateUser(String username, - User body); + default ResponseEntity updateUser(String username, + User body) { + return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); + + } } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java deleted file mode 100644 index 8f936b311447..000000000000 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/CustomInstantDeserializer.java +++ /dev/null @@ -1,232 +0,0 @@ -package org.openapitools.configuration; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonTokenId; -import com.fasterxml.jackson.databind.DeserializationContext; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonDeserializer; -import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; -import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; -import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; -import com.fasterxml.jackson.datatype.threetenbp.function.Function; -import org.threeten.bp.DateTimeException; -import org.threeten.bp.DateTimeUtils; -import org.threeten.bp.Instant; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZoneId; -import org.threeten.bp.ZonedDateTime; -import org.threeten.bp.format.DateTimeFormatter; -import org.threeten.bp.temporal.Temporal; -import org.threeten.bp.temporal.TemporalAccessor; - -import java.io.IOException; -import java.math.BigDecimal; - -/** - * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. - * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. - * - * @author Nick Williams - */ -public class CustomInstantDeserializer - extends ThreeTenDateTimeDeserializerBase { - private static final long serialVersionUID = 1L; - - public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( - Instant.class, DateTimeFormatter.ISO_INSTANT, - new Function() { - @Override - public Instant apply(TemporalAccessor temporalAccessor) { - return Instant.from(temporalAccessor); - } - }, - new Function() { - @Override - public Instant apply(FromIntegerArguments a) { - return Instant.ofEpochMilli(a.value); - } - }, - new Function() { - @Override - public Instant apply(FromDecimalArguments a) { - return Instant.ofEpochSecond(a.integer, a.fraction); - } - }, - null - ); - - public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( - OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, - new Function() { - @Override - public OffsetDateTime apply(TemporalAccessor temporalAccessor) { - return OffsetDateTime.from(temporalAccessor); - } - }, - new Function() { - @Override - public OffsetDateTime apply(FromIntegerArguments a) { - return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); - } - }, - new Function() { - @Override - public OffsetDateTime apply(FromDecimalArguments a) { - return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); - } - }, - new BiFunction() { - @Override - public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { - return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); - } - } - ); - - public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( - ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, - new Function() { - @Override - public ZonedDateTime apply(TemporalAccessor temporalAccessor) { - return ZonedDateTime.from(temporalAccessor); - } - }, - new Function() { - @Override - public ZonedDateTime apply(FromIntegerArguments a) { - return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); - } - }, - new Function() { - @Override - public ZonedDateTime apply(FromDecimalArguments a) { - return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); - } - }, - new BiFunction() { - @Override - public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { - return zonedDateTime.withZoneSameInstant(zoneId); - } - } - ); - - protected final Function fromMilliseconds; - - protected final Function fromNanoseconds; - - protected final Function parsedToValue; - - protected final BiFunction adjust; - - protected CustomInstantDeserializer(Class supportedType, - DateTimeFormatter parser, - Function parsedToValue, - Function fromMilliseconds, - Function fromNanoseconds, - BiFunction adjust) { - super(supportedType, parser); - this.parsedToValue = parsedToValue; - this.fromMilliseconds = fromMilliseconds; - this.fromNanoseconds = fromNanoseconds; - this.adjust = adjust == null ? new BiFunction() { - @Override - public T apply(T t, ZoneId zoneId) { - return t; - } - } : adjust; - } - - @SuppressWarnings("unchecked") - protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { - super((Class) base.handledType(), f); - parsedToValue = base.parsedToValue; - fromMilliseconds = base.fromMilliseconds; - fromNanoseconds = base.fromNanoseconds; - adjust = base.adjust; - } - - @Override - protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { - if (dtf == _formatter) { - return this; - } - return new CustomInstantDeserializer(this, dtf); - } - - @Override - public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { - //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only - //string values have to be adjusted to the configured TZ. - switch (parser.getCurrentTokenId()) { - case JsonTokenId.ID_NUMBER_FLOAT: { - BigDecimal value = parser.getDecimalValue(); - long seconds = value.longValue(); - int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); - return fromNanoseconds.apply(new FromDecimalArguments( - seconds, nanoseconds, getZone(context))); - } - - case JsonTokenId.ID_NUMBER_INT: { - long timestamp = parser.getLongValue(); - if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { - return this.fromNanoseconds.apply(new FromDecimalArguments( - timestamp, 0, this.getZone(context) - )); - } - return this.fromMilliseconds.apply(new FromIntegerArguments( - timestamp, this.getZone(context) - )); - } - - case JsonTokenId.ID_STRING: { - String string = parser.getText().trim(); - if (string.length() == 0) { - return null; - } - if (string.endsWith("+0000")) { - string = string.substring(0, string.length() - 5) + "Z"; - } - T value; - try { - TemporalAccessor acc = _formatter.parse(string); - value = parsedToValue.apply(acc); - if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { - return adjust.apply(value, this.getZone(context)); - } - } catch (DateTimeException e) { - throw _peelDTE(e); - } - return value; - } - } - throw context.mappingException("Expected type float, integer, or string."); - } - - private ZoneId getZone(DeserializationContext context) { - // Instants are always in UTC, so don't waste compute cycles - return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); - } - - private static class FromIntegerArguments { - public final long value; - public final ZoneId zoneId; - - private FromIntegerArguments(long value, ZoneId zoneId) { - this.value = value; - this.zoneId = zoneId; - } - } - - private static class FromDecimalArguments { - public final long integer; - public final int fraction; - public final ZoneId zoneId; - - private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { - this.integer = integer; - this.fraction = fraction; - this.zoneId = zoneId; - } - } -} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/JacksonConfiguration.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/JacksonConfiguration.java deleted file mode 100644 index b481a87518f4..000000000000 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/JacksonConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.openapitools.configuration; - -import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.threeten.bp.Instant; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZonedDateTime; - -@Configuration -public class JacksonConfiguration { - - @Bean - @ConditionalOnMissingBean(ThreeTenModule.class) - ThreeTenModule threeTenModule() { - ThreeTenModule module = new ThreeTenModule(); - module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); - module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); - module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); - return module; - } -} diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java index 425e530b93b1..589dd7dc5e7f 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java @@ -40,8 +40,9 @@ public Docket customImplementation(ServletContext servletContext, @Value("${open .select() .apis(RequestHandlerSelectors.basePackage("org.openapitools.api")) .build() - .directModelSubstitute(org.threeten.bp.LocalDate.class, java.sql.Date.class) - .directModelSubstitute(org.threeten.bp.OffsetDateTime.class, java.util.Date.class) + .pathProvider(new BasePathAwareRelativePathProvider(servletContext, basePath)) + .directModelSubstitute(java.time.LocalDate.class, java.sql.Date.class) + .directModelSubstitute(java.time.OffsetDateTime.class, java.util.Date.class) .apiInfo(apiInfo()); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java index 1e2c8c2726d3..76a9f4e4c256 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -66,7 +66,7 @@ public AdditionalPropertiesClass mapString(Map mapString) { public AdditionalPropertiesClass putMapStringItem(String key, String mapStringItem) { if (this.mapString == null) { - this.mapString = new HashMap(); + this.mapString = new HashMap<>(); } this.mapString.put(key, mapStringItem); return this; @@ -94,7 +94,7 @@ public AdditionalPropertiesClass mapNumber(Map mapNumber) { public AdditionalPropertiesClass putMapNumberItem(String key, BigDecimal mapNumberItem) { if (this.mapNumber == null) { - this.mapNumber = new HashMap(); + this.mapNumber = new HashMap<>(); } this.mapNumber.put(key, mapNumberItem); return this; @@ -123,7 +123,7 @@ public AdditionalPropertiesClass mapInteger(Map mapInteger) { public AdditionalPropertiesClass putMapIntegerItem(String key, Integer mapIntegerItem) { if (this.mapInteger == null) { - this.mapInteger = new HashMap(); + this.mapInteger = new HashMap<>(); } this.mapInteger.put(key, mapIntegerItem); return this; @@ -151,7 +151,7 @@ public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { public AdditionalPropertiesClass putMapBooleanItem(String key, Boolean mapBooleanItem) { if (this.mapBoolean == null) { - this.mapBoolean = new HashMap(); + this.mapBoolean = new HashMap<>(); } this.mapBoolean.put(key, mapBooleanItem); return this; @@ -179,7 +179,7 @@ public AdditionalPropertiesClass mapArrayInteger(Map> mapA public AdditionalPropertiesClass putMapArrayIntegerItem(String key, List mapArrayIntegerItem) { if (this.mapArrayInteger == null) { - this.mapArrayInteger = new HashMap>(); + this.mapArrayInteger = new HashMap<>(); } this.mapArrayInteger.put(key, mapArrayIntegerItem); return this; @@ -208,7 +208,7 @@ public AdditionalPropertiesClass mapArrayAnytype(Map> mapAr public AdditionalPropertiesClass putMapArrayAnytypeItem(String key, List mapArrayAnytypeItem) { if (this.mapArrayAnytype == null) { - this.mapArrayAnytype = new HashMap>(); + this.mapArrayAnytype = new HashMap<>(); } this.mapArrayAnytype.put(key, mapArrayAnytypeItem); return this; @@ -237,7 +237,7 @@ public AdditionalPropertiesClass mapMapString(Map> m public AdditionalPropertiesClass putMapMapStringItem(String key, Map mapMapStringItem) { if (this.mapMapString == null) { - this.mapMapString = new HashMap>(); + this.mapMapString = new HashMap<>(); } this.mapMapString.put(key, mapMapStringItem); return this; @@ -266,7 +266,7 @@ public AdditionalPropertiesClass mapMapAnytype(Map> public AdditionalPropertiesClass putMapMapAnytypeItem(String key, Map mapMapAnytypeItem) { if (this.mapMapAnytype == null) { - this.mapMapAnytype = new HashMap>(); + this.mapMapAnytype = new HashMap<>(); } this.mapMapAnytype.put(key, mapMapAnytypeItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 9c226efbbc46..aec96b23f033 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -28,7 +28,7 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList>(); + this.arrayArrayNumber = new ArrayList<>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java index 51ea58aab386..63a657c8dddf 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -28,7 +28,7 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList(); + this.arrayNumber = new ArrayList<>(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java index 1fea247ab3ca..2a36629dfc75 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java @@ -36,7 +36,7 @@ public ArrayTest arrayOfString(List arrayOfString) { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList(); + this.arrayOfString = new ArrayList<>(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -64,7 +64,7 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList>(); + this.arrayArrayOfInteger = new ArrayList<>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -93,7 +93,7 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList>(); + this.arrayArrayOfModel = new ArrayList<>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/EnumArrays.java index 90d7bf130bb1..ec2d4e1ce8b9 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/EnumArrays.java @@ -121,7 +121,7 @@ public EnumArrays arrayEnum(List arrayEnum) { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList(); + this.arrayEnum = new ArrayList<>(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FileSchemaTestClass.java index a99196c28084..8e4f8d5d5d9d 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FileSchemaTestClass.java @@ -51,7 +51,7 @@ public FileSchemaTestClass files(List files) { public FileSchemaTestClass addFilesItem(java.io.File filesItem) { if (this.files == null) { - this.files = new ArrayList(); + this.files = new ArrayList<>(); } this.files.add(filesItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java index 533569e421dc..55298e86211e 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java @@ -6,10 +6,10 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; import java.util.UUID; import org.springframework.core.io.Resource; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MapTest.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MapTest.java index b1d48c044ada..7b9a321ecb22 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MapTest.java @@ -76,7 +76,7 @@ public MapTest mapMapOfString(Map> mapMapOfString) { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap>(); + this.mapMapOfString = new HashMap<>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -105,7 +105,7 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap(); + this.mapOfEnumString = new HashMap<>(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; @@ -133,7 +133,7 @@ public MapTest directMap(Map directMap) { public MapTest putDirectMapItem(String key, Boolean directMapItem) { if (this.directMap == null) { - this.directMap = new HashMap(); + this.directMap = new HashMap<>(); } this.directMap.put(key, directMapItem); return this; @@ -161,7 +161,7 @@ public MapTest indirectMap(Map indirectMap) { public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { if (this.indirectMap == null) { - this.indirectMap = new HashMap(); + this.indirectMap = new HashMap<>(); } this.indirectMap.put(key, indirectMapItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 71693227fa7a..d80573256c63 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -5,12 +5,12 @@ import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.openapitools.model.Animal; -import org.threeten.bp.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; @@ -80,7 +80,7 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.map.put(key, mapItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Order.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Order.java index 06a8fdb89353..0c9dddf85daf 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Order.java @@ -6,7 +6,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; import org.openapitools.jackson.nullable.JsonNullable; import javax.validation.Valid; import javax.validation.constraints.*; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Pet.java index 5f8b54eb5734..5f44cab5669e 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/Pet.java @@ -32,7 +32,7 @@ public class Pet { @JsonProperty("photoUrls") @Valid - private Set photoUrls = new LinkedHashSet(); + private Set photoUrls = new LinkedHashSet<>(); @JsonProperty("tags") @Valid @@ -173,7 +173,7 @@ public Pet tags(List tags) { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList(); + this.tags = new ArrayList<>(); } this.tags.add(tagsItem); return this; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderDefault.java index bcf00b393fd4..80788f31612a 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderDefault.java @@ -31,7 +31,7 @@ public class TypeHolderDefault { @JsonProperty("array_item") @Valid - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderDefault stringItem(String stringItem) { this.stringItem = stringItem; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderExample.java index 2151f844f8ed..963c3c66b57b 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/TypeHolderExample.java @@ -34,7 +34,7 @@ public class TypeHolderExample { @JsonProperty("array_item") @Valid - private List arrayItem = new ArrayList(); + private List arrayItem = new ArrayList<>(); public TypeHolderExample stringItem(String stringItem) { this.stringItem = stringItem; diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/XmlItem.java index 9240d5345a67..465b94b6a88d 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/XmlItem.java @@ -201,7 +201,7 @@ public XmlItem wrappedArray(List wrappedArray) { public XmlItem addWrappedArrayItem(Integer wrappedArrayItem) { if (this.wrappedArray == null) { - this.wrappedArray = new ArrayList(); + this.wrappedArray = new ArrayList<>(); } this.wrappedArray.add(wrappedArrayItem); return this; @@ -310,7 +310,7 @@ public XmlItem nameArray(List nameArray) { public XmlItem addNameArrayItem(Integer nameArrayItem) { if (this.nameArray == null) { - this.nameArray = new ArrayList(); + this.nameArray = new ArrayList<>(); } this.nameArray.add(nameArrayItem); return this; @@ -338,7 +338,7 @@ public XmlItem nameWrappedArray(List nameWrappedArray) { public XmlItem addNameWrappedArrayItem(Integer nameWrappedArrayItem) { if (this.nameWrappedArray == null) { - this.nameWrappedArray = new ArrayList(); + this.nameWrappedArray = new ArrayList<>(); } this.nameWrappedArray.add(nameWrappedArrayItem); return this; @@ -447,7 +447,7 @@ public XmlItem prefixArray(List prefixArray) { public XmlItem addPrefixArrayItem(Integer prefixArrayItem) { if (this.prefixArray == null) { - this.prefixArray = new ArrayList(); + this.prefixArray = new ArrayList<>(); } this.prefixArray.add(prefixArrayItem); return this; @@ -475,7 +475,7 @@ public XmlItem prefixWrappedArray(List prefixWrappedArray) { public XmlItem addPrefixWrappedArrayItem(Integer prefixWrappedArrayItem) { if (this.prefixWrappedArray == null) { - this.prefixWrappedArray = new ArrayList(); + this.prefixWrappedArray = new ArrayList<>(); } this.prefixWrappedArray.add(prefixWrappedArrayItem); return this; @@ -584,7 +584,7 @@ public XmlItem namespaceArray(List namespaceArray) { public XmlItem addNamespaceArrayItem(Integer namespaceArrayItem) { if (this.namespaceArray == null) { - this.namespaceArray = new ArrayList(); + this.namespaceArray = new ArrayList<>(); } this.namespaceArray.add(namespaceArrayItem); return this; @@ -612,7 +612,7 @@ public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { public XmlItem addNamespaceWrappedArrayItem(Integer namespaceWrappedArrayItem) { if (this.namespaceWrappedArray == null) { - this.namespaceWrappedArray = new ArrayList(); + this.namespaceWrappedArray = new ArrayList<>(); } this.namespaceWrappedArray.add(namespaceWrappedArrayItem); return this; @@ -721,7 +721,7 @@ public XmlItem prefixNsArray(List prefixNsArray) { public XmlItem addPrefixNsArrayItem(Integer prefixNsArrayItem) { if (this.prefixNsArray == null) { - this.prefixNsArray = new ArrayList(); + this.prefixNsArray = new ArrayList<>(); } this.prefixNsArray.add(prefixNsArrayItem); return this; @@ -749,7 +749,7 @@ public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { if (this.prefixNsWrappedArray == null) { - this.prefixNsWrappedArray = new ArrayList(); + this.prefixNsWrappedArray = new ArrayList<>(); } this.prefixNsWrappedArray.add(prefixNsWrappedArrayItem); return this; From f681016ffd63872da714e7ce46e9a6d028544dab Mon Sep 17 00:00:00 2001 From: Richard Kolkovich Date: Fri, 28 Aug 2020 09:19:53 -0600 Subject: [PATCH 08/11] Fix typescript-node generation when only models are generated (#7127) * add model/index.ts - move export of all models to model/index.ts - move RequestFile definition to model/index.ts This fixes #7126 * update samples * Back out models/index.ts Make this backwards-compatible: - move `RequestFile` definition to `model/models.ts` - remove `model/index.ts` - re-export `RequestFile` from `api/apis.ts` - make generation of `ObjectSerializer` conditional * for some reason, Symfony isn't up to date * reverts changes to php-symfony sample * moves comment to mustache comment rather than TS comment Co-authored-by: Esteban Gehring * removes stale files from samples (no longer generated) * updates samples Co-authored-by: Esteban Gehring --- .../typescript-node/api-all.mustache | 11 +--------- .../resources/typescript-node/model.mustache | 4 ++-- .../resources/typescript-node/models.mustache | 20 ++++++++++++++++++- .../typescript-node/default/api/apis.ts | 11 +--------- .../default/model/apiResponse.ts | 2 +- .../typescript-node/default/model/category.ts | 2 +- .../typescript-node/default/model/models.ts | 15 +++++++++++++- .../typescript-node/default/model/order.ts | 2 +- .../typescript-node/default/model/pet.ts | 2 +- .../typescript-node/default/model/tag.ts | 2 +- .../typescript-node/default/model/user.ts | 2 +- .../petstore/typescript-node/npm/api/apis.ts | 11 +--------- .../typescript-node/npm/model/apiResponse.ts | 2 +- .../typescript-node/npm/model/category.ts | 2 +- .../typescript-node/npm/model/models.ts | 15 +++++++++++++- .../typescript-node/npm/model/order.ts | 2 +- .../petstore/typescript-node/npm/model/pet.ts | 2 +- .../petstore/typescript-node/npm/model/tag.ts | 2 +- .../typescript-node/npm/model/user.ts | 2 +- 19 files changed, 64 insertions(+), 47 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/typescript-node/api-all.mustache b/modules/openapi-generator/src/main/resources/typescript-node/api-all.mustache index 0f63a320cd1d..16b585d9e4e7 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/api-all.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/api-all.mustache @@ -8,7 +8,6 @@ import { {{ classname }} } from './{{ classFilename }}'; export * from './{{ classFilename }}Interface' {{/withInterfaces}} {{/apis}} -import * as fs from 'fs'; import * as http from 'http'; export class HttpError extends Error { @@ -18,15 +17,7 @@ export class HttpError extends Error { } } -export interface RequestDetailedFile { - value: Buffer; - options?: { - filename?: string; - contentType?: string; - } -} - -export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; +export { RequestFile } from '../model/models'; export const APIS = [{{#apis}}{{#operations}}{{ classname }}{{/operations}}{{^-last}}, {{/-last}}{{/apis}}]; {{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/typescript-node/model.mustache b/modules/openapi-generator/src/main/resources/typescript-node/model.mustache index 521bce34d767..e728b68ac4c0 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/model.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/model.mustache @@ -1,7 +1,7 @@ {{>licenseInfo}} {{#models}} {{#model}} -import { RequestFile } from '../api'; +import { RequestFile } from './models'; {{#tsImports}} import { {{classname}} } from '{{filename}}'; {{/tsImports}} @@ -78,4 +78,4 @@ export enum {{classname}} { } {{/isEnum}} {{/model}} -{{/models}} \ No newline at end of file +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/typescript-node/models.mustache b/modules/openapi-generator/src/main/resources/typescript-node/models.mustache index 41bf1422eab8..93f3790d667d 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/models.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/models.mustache @@ -1,10 +1,27 @@ +{{#generateApis}} +import localVarRequest from 'request'; +{{/generateApis}} + {{#models}} {{#model}} export * from '{{{ classFilename }}}'; {{/model}} {{/models}} -import localVarRequest from 'request'; +import * as fs from 'fs'; + +export interface RequestDetailedFile { + value: Buffer; + options?: { + filename?: string; + contentType?: string; + } +} + +export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; + +{{! Object serialization only relevant if generating APIs, too }} +{{#generateApis}} {{#models}} {{#model}} @@ -235,3 +252,4 @@ export class VoidAuth implements Authentication { } export type Interceptor = (requestOptions: localVarRequest.Options) => (Promise | void); +{{/generateApis}} diff --git a/samples/client/petstore/typescript-node/default/api/apis.ts b/samples/client/petstore/typescript-node/default/api/apis.ts index eef2cffcc297..3faa8c47b335 100644 --- a/samples/client/petstore/typescript-node/default/api/apis.ts +++ b/samples/client/petstore/typescript-node/default/api/apis.ts @@ -4,7 +4,6 @@ export * from './storeApi'; import { StoreApi } from './storeApi'; export * from './userApi'; import { UserApi } from './userApi'; -import * as fs from 'fs'; import * as http from 'http'; export class HttpError extends Error { @@ -14,14 +13,6 @@ export class HttpError extends Error { } } -export interface RequestDetailedFile { - value: Buffer; - options?: { - filename?: string; - contentType?: string; - } -} - -export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; +export { RequestFile } from '../model/models'; export const APIS = [PetApi, StoreApi, UserApi]; diff --git a/samples/client/petstore/typescript-node/default/model/apiResponse.ts b/samples/client/petstore/typescript-node/default/model/apiResponse.ts index ae84669a8422..aa4047061f9c 100644 --- a/samples/client/petstore/typescript-node/default/model/apiResponse.ts +++ b/samples/client/petstore/typescript-node/default/model/apiResponse.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * Describes the result of uploading an image resource diff --git a/samples/client/petstore/typescript-node/default/model/category.ts b/samples/client/petstore/typescript-node/default/model/category.ts index 1babd0fd22e3..facdc9d479f6 100644 --- a/samples/client/petstore/typescript-node/default/model/category.ts +++ b/samples/client/petstore/typescript-node/default/model/category.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * A category for a pet diff --git a/samples/client/petstore/typescript-node/default/model/models.ts b/samples/client/petstore/typescript-node/default/model/models.ts index 1da13addd120..ba05217de7e8 100644 --- a/samples/client/petstore/typescript-node/default/model/models.ts +++ b/samples/client/petstore/typescript-node/default/model/models.ts @@ -1,3 +1,5 @@ +import localVarRequest from 'request'; + export * from './apiResponse'; export * from './category'; export * from './order'; @@ -5,7 +7,18 @@ export * from './pet'; export * from './tag'; export * from './user'; -import localVarRequest from 'request'; +import * as fs from 'fs'; + +export interface RequestDetailedFile { + value: Buffer; + options?: { + filename?: string; + contentType?: string; + } +} + +export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; + import { ApiResponse } from './apiResponse'; import { Category } from './category'; diff --git a/samples/client/petstore/typescript-node/default/model/order.ts b/samples/client/petstore/typescript-node/default/model/order.ts index 1ee3ea280c61..18d5a8f2e861 100644 --- a/samples/client/petstore/typescript-node/default/model/order.ts +++ b/samples/client/petstore/typescript-node/default/model/order.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * An order for a pets from the pet store diff --git a/samples/client/petstore/typescript-node/default/model/pet.ts b/samples/client/petstore/typescript-node/default/model/pet.ts index 141c4ebc17c9..10fd0c33207b 100644 --- a/samples/client/petstore/typescript-node/default/model/pet.ts +++ b/samples/client/petstore/typescript-node/default/model/pet.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; import { Category } from './category'; import { Tag } from './tag'; diff --git a/samples/client/petstore/typescript-node/default/model/tag.ts b/samples/client/petstore/typescript-node/default/model/tag.ts index 96e644974ef1..6b0f9752ee90 100644 --- a/samples/client/petstore/typescript-node/default/model/tag.ts +++ b/samples/client/petstore/typescript-node/default/model/tag.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * A tag for a pet diff --git a/samples/client/petstore/typescript-node/default/model/user.ts b/samples/client/petstore/typescript-node/default/model/user.ts index 62b0b6436898..0b1401384c07 100644 --- a/samples/client/petstore/typescript-node/default/model/user.ts +++ b/samples/client/petstore/typescript-node/default/model/user.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * A User who is purchasing from the pet store diff --git a/samples/client/petstore/typescript-node/npm/api/apis.ts b/samples/client/petstore/typescript-node/npm/api/apis.ts index eef2cffcc297..3faa8c47b335 100644 --- a/samples/client/petstore/typescript-node/npm/api/apis.ts +++ b/samples/client/petstore/typescript-node/npm/api/apis.ts @@ -4,7 +4,6 @@ export * from './storeApi'; import { StoreApi } from './storeApi'; export * from './userApi'; import { UserApi } from './userApi'; -import * as fs from 'fs'; import * as http from 'http'; export class HttpError extends Error { @@ -14,14 +13,6 @@ export class HttpError extends Error { } } -export interface RequestDetailedFile { - value: Buffer; - options?: { - filename?: string; - contentType?: string; - } -} - -export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; +export { RequestFile } from '../model/models'; export const APIS = [PetApi, StoreApi, UserApi]; diff --git a/samples/client/petstore/typescript-node/npm/model/apiResponse.ts b/samples/client/petstore/typescript-node/npm/model/apiResponse.ts index ae84669a8422..aa4047061f9c 100644 --- a/samples/client/petstore/typescript-node/npm/model/apiResponse.ts +++ b/samples/client/petstore/typescript-node/npm/model/apiResponse.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * Describes the result of uploading an image resource diff --git a/samples/client/petstore/typescript-node/npm/model/category.ts b/samples/client/petstore/typescript-node/npm/model/category.ts index 1babd0fd22e3..facdc9d479f6 100644 --- a/samples/client/petstore/typescript-node/npm/model/category.ts +++ b/samples/client/petstore/typescript-node/npm/model/category.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * A category for a pet diff --git a/samples/client/petstore/typescript-node/npm/model/models.ts b/samples/client/petstore/typescript-node/npm/model/models.ts index 1da13addd120..ba05217de7e8 100644 --- a/samples/client/petstore/typescript-node/npm/model/models.ts +++ b/samples/client/petstore/typescript-node/npm/model/models.ts @@ -1,3 +1,5 @@ +import localVarRequest from 'request'; + export * from './apiResponse'; export * from './category'; export * from './order'; @@ -5,7 +7,18 @@ export * from './pet'; export * from './tag'; export * from './user'; -import localVarRequest from 'request'; +import * as fs from 'fs'; + +export interface RequestDetailedFile { + value: Buffer; + options?: { + filename?: string; + contentType?: string; + } +} + +export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; + import { ApiResponse } from './apiResponse'; import { Category } from './category'; diff --git a/samples/client/petstore/typescript-node/npm/model/order.ts b/samples/client/petstore/typescript-node/npm/model/order.ts index 1ee3ea280c61..18d5a8f2e861 100644 --- a/samples/client/petstore/typescript-node/npm/model/order.ts +++ b/samples/client/petstore/typescript-node/npm/model/order.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * An order for a pets from the pet store diff --git a/samples/client/petstore/typescript-node/npm/model/pet.ts b/samples/client/petstore/typescript-node/npm/model/pet.ts index 141c4ebc17c9..10fd0c33207b 100644 --- a/samples/client/petstore/typescript-node/npm/model/pet.ts +++ b/samples/client/petstore/typescript-node/npm/model/pet.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; import { Category } from './category'; import { Tag } from './tag'; diff --git a/samples/client/petstore/typescript-node/npm/model/tag.ts b/samples/client/petstore/typescript-node/npm/model/tag.ts index 96e644974ef1..6b0f9752ee90 100644 --- a/samples/client/petstore/typescript-node/npm/model/tag.ts +++ b/samples/client/petstore/typescript-node/npm/model/tag.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * A tag for a pet diff --git a/samples/client/petstore/typescript-node/npm/model/user.ts b/samples/client/petstore/typescript-node/npm/model/user.ts index 62b0b6436898..0b1401384c07 100644 --- a/samples/client/petstore/typescript-node/npm/model/user.ts +++ b/samples/client/petstore/typescript-node/npm/model/user.ts @@ -10,7 +10,7 @@ * Do not edit the class manually. */ -import { RequestFile } from '../api'; +import { RequestFile } from './models'; /** * A User who is purchasing from the pet store From 2c656052899beae8e42dace0aebcbdec8ec60f2d Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Sat, 29 Aug 2020 00:17:55 +0800 Subject: [PATCH 09/11] [C][Client][Clang Static Analyzer] Remove the useless free operation for (#7309) buffContent --- .../src/main/resources/C-libcurl/apiClient.c.mustache | 4 ---- samples/client/petstore/c/src/apiClient.c | 4 ---- 2 files changed, 8 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache index 900a986cb081..f8f374d23a08 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/apiClient.c.mustache @@ -520,10 +520,6 @@ void apiClient_invoke(apiClient_t *apiClient, free(targetUrl); - if(contentType != NULL) { - free(buffContent); - } - if(res == CURLE_OK) { curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &apiClient->response_code); } else { diff --git a/samples/client/petstore/c/src/apiClient.c b/samples/client/petstore/c/src/apiClient.c index e156bc53b959..cb77e9c61987 100644 --- a/samples/client/petstore/c/src/apiClient.c +++ b/samples/client/petstore/c/src/apiClient.c @@ -437,10 +437,6 @@ void apiClient_invoke(apiClient_t *apiClient, free(targetUrl); - if(contentType != NULL) { - free(buffContent); - } - if(res == CURLE_OK) { curl_easy_getinfo(handle, CURLINFO_RESPONSE_CODE, &apiClient->response_code); } else { From da9f2f7c9bb560b573d462b639c02e3489b5618d Mon Sep 17 00:00:00 2001 From: Yuriy Belenko Date: Fri, 28 Aug 2020 19:27:03 +0300 Subject: [PATCH 10/11] [php-slim4] Move config to a separate file (#6971) * Move config into separated file * Restrict access from web to config folder * Exclude config folder from code base * Update documentation * Refresh samples * Fix misplaced pathes --- .../languages/PhpSlim4ServerCodegen.java | 3 + .../php-slim4-server/README.mustache | 28 +++--- .../php-slim4-server/config_example.mustache | 83 ++++++++++++++++ .../main/resources/php-slim4-server/gitignore | 8 +- .../php-slim4-server/htaccess_deny_all | 1 + .../resources/php-slim4-server/index.mustache | 83 +++------------- samples/server/petstore/php-slim4/.gitignore | 8 +- .../php-slim4/.openapi-generator/FILES | 3 + samples/server/petstore/php-slim4/README.md | 28 +++--- .../petstore/php-slim4/config/.htaccess | 1 + .../php-slim4/config/dev/example.inc.php | 96 +++++++++++++++++++ .../php-slim4/config/prod/example.inc.php | 96 +++++++++++++++++++ samples/server/petstore/php-slim4/index.php | 83 +++------------- 13 files changed, 349 insertions(+), 172 deletions(-) create mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/config_example.mustache create mode 100644 modules/openapi-generator/src/main/resources/php-slim4-server/htaccess_deny_all create mode 100644 samples/server/petstore/php-slim4/config/.htaccess create mode 100644 samples/server/petstore/php-slim4/config/dev/example.inc.php create mode 100644 samples/server/petstore/php-slim4/config/prod/example.inc.php diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java index d79b7f98ef3e..1c4a9e1295b8 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSlim4ServerCodegen.java @@ -123,6 +123,9 @@ public void processOpts() { // Slim 4 doesn't parse JSON body anymore we need to add suggested middleware // ref: https://www.slimframework.com/docs/v4/objects/request.html#the-request-body + supportingFiles.add(new SupportingFile("htaccess_deny_all", "config", ".htaccess")); + supportingFiles.add(new SupportingFile("config_example.mustache", "config" + File.separator + "dev", "example.inc.php")); + supportingFiles.add(new SupportingFile("config_example.mustache", "config" + File.separator + "prod", "example.inc.php")); supportingFiles.add(new SupportingFile("json_body_parser_middleware.mustache", toSrcPath(invokerPackage + "\\Middleware", srcBasePath), "JsonBodyParserMiddleware.php")); supportingFiles.add(new SupportingFile("base_model.mustache", toSrcPath(invokerPackage, srcBasePath), "BaseModel.php")); supportingFiles.add(new SupportingFile("base_model_test.mustache", toSrcPath(invokerPackage, testBasePath), "BaseModelTest.php")); diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache index 6746071f556f..cd4369807b89 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/README.mustache @@ -32,6 +32,10 @@ This command downloads the Slim Framework and its third-party dependencies into $ composer install ``` +## Add configs + +Application requires at least one config file(`config/dev/config.inc.php` or `config/prod/config.inc.php`). You can use [config/dev/example.inc.php](config/dev/example.inc.php) as starting point. + ## Start devserver Run the following command in terminal to start localhost web server, assuming `./php-slim-server/` is public-accessible directory with `index.php` file: @@ -93,25 +97,19 @@ $ composer phplint ## Show errors -Switch on option in `./index.php`: +Switch on option in your application config file like: ```diff -/** - * Add Error Handling Middleware - * - * @param bool $displayErrorDetails -> Should be set to false in production - * @param bool $logErrors -> Parameter is passed to the default ErrorHandler - * @param bool $logErrorDetails -> Display error details in error log - * which can be replaced by a callable of your choice. - - * Note: This middleware should be added last. It will not handle any exceptions/errors - * for middleware added after it. - */ ---- $app->addErrorMiddleware(false, true, true); -+++ $app->addErrorMiddleware(true, true, true); + return [ + 'slimSettings' => [ +- 'displayErrorDetails' => false, ++ 'displayErrorDetails' => true, + 'logErrors' => true, + 'logErrorDetails' => true, + ], ``` ## Mock Server -For a quick start uncomment [mocker middleware config](index.php#L62-L89). +For a quick start uncomment [mocker middleware options](config/dev/example.inc.php#L67-L94) in your application config file. Used packages: * [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator. diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/config_example.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/config_example.mustache new file mode 100644 index 000000000000..3060299af9c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/config_example.mustache @@ -0,0 +1,83 @@ +licenseInfo}} + +/** + * App configuration file example. + * + * Copy file to config/dev/config.inc.php and config/prod/config.inc.php + * App loads dev config only when prod doesn't exist + * in other words if both configs presented - prod config applies + */ + +use Psr\Http\Message\ServerRequestInterface; +use Psr\Http\Message\ResponseInterface; +use OpenAPIServer\Mock\OpenApiDataMocker; + +$mocker = new OpenApiDataMocker(); +$mocker->setModelsNamespace('{{modelPackage}}\\'); + +return [ + 'slimSettings' => [ + 'displayErrorDetails' => false, + 'logErrors' => true, + 'logErrorDetails' => true, + ], + + 'tokenAuthenticationOptions' => [ + /** + * Tokens are essentially passwords. You should treat them as such and you should always + * use HTTPS. If the middleware detects insecure usage over HTTP it will return unauthorized + * with a message Required HTTPS for token authentication. This rule is relaxed for requests + * on localhost. To allow insecure usage you must enable it manually by setting secure to + * false. + * Default: true + */ + // 'secure' => true, + + /** + * Alternatively you can list your development host to have relaxed security. + * Default: ['localhost', '127.0.0.1'] + */ + // 'relaxed' => ['localhost', '127.0.0.1'], + + /** + * By default on ocurred a fail on authentication, is sent a response on json format with a + * message (`Invalid Token` or `Not found Token`) and with the token (if found), with status + * `401 Unauthorized`. You can customize it by setting a callable function on error option. + * Default: null + */ + // 'error' => null, + ], + + 'mockerOptions' => [ + // 'dataMocker' => $mocker, + + // 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, array $responses) { + // // check if client clearly asks for mocked response + // $pingHeader = 'X-{{invokerPackage}}-Mock'; + // $pingHeaderCode = 'X-{{invokerPackage}}-Mock-Code'; + // if ( + // $request->hasHeader($pingHeader) + // && $request->getHeader($pingHeader)[0] === 'ping' + // ) { + // $responses = (array) $responses; + // $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default'; + // if (array_key_exists($requestedResponseCode, $responses)) { + // return $requestedResponseCode; + // } + + // // return first response key + // reset($responses); + // return key($responses); + // } + + // return false; + // }, + + // 'afterCallback' => function (ServerRequestInterface $request, ResponseInterface $response) { + // // mark mocked response to distinguish real and fake responses + // return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong'); + // }, + ], +]; diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/gitignore b/modules/openapi-generator/src/main/resources/php-slim4-server/gitignore index f55680b5277b..e12b356ade0a 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/gitignore +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/gitignore @@ -15,4 +15,10 @@ composer.phar /.phpunit.result.cache # Do not commit local PHP_CodeSniffer config -/phpcs.xml \ No newline at end of file +/phpcs.xml + +# Application config may contain sensitive data +/config/**/*.* +!/config/.htaccess +!/config/dev/example.inc.php +!/config/prod/example.inc.php diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/htaccess_deny_all b/modules/openapi-generator/src/main/resources/php-slim4-server/htaccess_deny_all new file mode 100644 index 000000000000..3a4288278871 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/htaccess_deny_all @@ -0,0 +1 @@ +Deny from all diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache index 1175d76e7bfa..4b3cfcaeecb9 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/index.mustache @@ -15,76 +15,15 @@ use Psr\Http\Message\ResponseInterface; use OpenAPIServer\Mock\OpenApiDataMocker; {{/apiInfo}} +// load config file $config = []; - -/** - * Token Middleware 1.x Options - * Options `header`, `regex`, `parameter`, `cookie`, `attribute`, `path`, `except`, `authenticator` - * are handled by SlimRouter class. These options are ignored by app and they omitted from current - * example. - * Ref: https://github.com/dyorg/slim-token-authentication/tree/1.x - */ -$config['tokenAuthenticationOptions'] = [ - /** - * Tokens are essentially passwords. You should treat them as such and you should always - * use HTTPS. If the middleware detects insecure usage over HTTP it will return unathorized - * with a message Required HTTPS for token authentication. This rule is relaxed for requests - * on localhost. To allow insecure usage you must enable it manually by setting secure to - * false. - * Default: true - */ - // 'secure' => true, - - /** - * Alternatively you can list your development host to have relaxed security. - * Default: ['localhost', '127.0.0.1'] - */ - // 'relaxed' => ['localhost', '127.0.0.1'], - - /** - * By default on ocurred a fail on authentication, is sent a response on json format with a - * message (`Invalid Token` or `Not found Token`) and with the token (if found), with status - * `401 Unauthorized`. You can customize it by setting a callable function on error option. - * Default: null - */ - // 'error' => null, -]; - -/** - * Mocker Middleware options. - */ -$mocker = new OpenApiDataMocker(); -$mocker->setModelsNamespace('{{modelPackage}}\\'); -$config['mockerOptions'] = [ - // 'dataMocker' => $mocker, - - // 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, $responses) { - // // check if client clearly asks for mocked response - // $pingHeader = 'X-{{invokerPackage}}-Mock'; - // $pingHeaderCode = 'X-{{invokerPackage}}-Mock-Code'; - // if ( - // $request->hasHeader($pingHeader) - // && $request->getHeader($pingHeader)[0] === 'ping' - // ) { - // $responses = (array) $responses; - // $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default'; - // if (array_key_exists($requestedResponseCode, $responses)) { - // return $requestedResponseCode; - // } - - // // return first response key - // reset($responses); - // return key($responses); - // } - - // return false; - // }, - - // 'afterCallback' => function ($request, $response) { - // // mark mocked response to distinguish real and fake responses - // return $response->withHeader('X-{{invokerPackage}}-Mock', 'pong'); - // }, -]; +if (is_array($prodConfig = @include(__DIR__ . '/config/prod/config.inc.php'))) { + $config = $prodConfig; +} elseif (is_array($devConfig = @include(__DIR__ . '/config/dev/config.inc.php'))) { + $config = $devConfig; +} else { + throw new InvalidArgumentException('Config file missed or broken.'); +} $router = new SlimRouter($config); $app = $router->getSlimApp(); @@ -106,6 +45,10 @@ $app->addRoutingMiddleware(); * Note: This middleware should be added last. It will not handle any exceptions/errors * for middleware added after it. */ -$app->addErrorMiddleware(false, true, true); +$app->addErrorMiddleware( + $config['slimSettings']['displayErrorDetails'] ?? false, + $config['slimSettings']['logErrors'] ?? true, + $config['slimSettings']['logErrorDetails'] ?? true +); $app->run(); diff --git a/samples/server/petstore/php-slim4/.gitignore b/samples/server/petstore/php-slim4/.gitignore index f55680b5277b..e12b356ade0a 100644 --- a/samples/server/petstore/php-slim4/.gitignore +++ b/samples/server/petstore/php-slim4/.gitignore @@ -15,4 +15,10 @@ composer.phar /.phpunit.result.cache # Do not commit local PHP_CodeSniffer config -/phpcs.xml \ No newline at end of file +/phpcs.xml + +# Application config may contain sensitive data +/config/**/*.* +!/config/.htaccess +!/config/dev/example.inc.php +!/config/prod/example.inc.php diff --git a/samples/server/petstore/php-slim4/.openapi-generator/FILES b/samples/server/petstore/php-slim4/.openapi-generator/FILES index 781243bb5264..bc363030f7ac 100644 --- a/samples/server/petstore/php-slim4/.openapi-generator/FILES +++ b/samples/server/petstore/php-slim4/.openapi-generator/FILES @@ -2,6 +2,9 @@ .htaccess README.md composer.json +config/.htaccess +config/dev/example.inc.php +config/prod/example.inc.php index.php lib/Api/AbstractPetApi.php lib/Api/AbstractStoreApi.php diff --git a/samples/server/petstore/php-slim4/README.md b/samples/server/petstore/php-slim4/README.md index 6a8bd154ccb9..a1bf87063b39 100644 --- a/samples/server/petstore/php-slim4/README.md +++ b/samples/server/petstore/php-slim4/README.md @@ -21,6 +21,10 @@ This command downloads the Slim Framework and its third-party dependencies into $ composer install ``` +## Add configs + +Application requires at least one config file(`config/dev/config.inc.php` or `config/prod/config.inc.php`). You can use [config/dev/example.inc.php](config/dev/example.inc.php) as starting point. + ## Start devserver Run the following command in terminal to start localhost web server, assuming `./php-slim-server/` is public-accessible directory with `index.php` file: @@ -82,25 +86,19 @@ $ composer phplint ## Show errors -Switch on option in `./index.php`: +Switch on option in your application config file like: ```diff -/** - * Add Error Handling Middleware - * - * @param bool $displayErrorDetails -> Should be set to false in production - * @param bool $logErrors -> Parameter is passed to the default ErrorHandler - * @param bool $logErrorDetails -> Display error details in error log - * which can be replaced by a callable of your choice. - - * Note: This middleware should be added last. It will not handle any exceptions/errors - * for middleware added after it. - */ ---- $app->addErrorMiddleware(false, true, true); -+++ $app->addErrorMiddleware(true, true, true); + return [ + 'slimSettings' => [ +- 'displayErrorDetails' => false, ++ 'displayErrorDetails' => true, + 'logErrors' => true, + 'logErrorDetails' => true, + ], ``` ## Mock Server -For a quick start uncomment [mocker middleware config](index.php#L62-L89). +For a quick start uncomment [mocker middleware options](config/dev/example.inc.php#L67-L94) in your application config file. Used packages: * [Openapi Data Mocker](https://github.com/ybelenko/openapi-data-mocker) - first implementation of OAS3 fake data generator. diff --git a/samples/server/petstore/php-slim4/config/.htaccess b/samples/server/petstore/php-slim4/config/.htaccess new file mode 100644 index 000000000000..3a4288278871 --- /dev/null +++ b/samples/server/petstore/php-slim4/config/.htaccess @@ -0,0 +1 @@ +Deny from all diff --git a/samples/server/petstore/php-slim4/config/dev/example.inc.php b/samples/server/petstore/php-slim4/config/dev/example.inc.php new file mode 100644 index 000000000000..0bbdd0810c86 --- /dev/null +++ b/samples/server/petstore/php-slim4/config/dev/example.inc.php @@ -0,0 +1,96 @@ +setModelsNamespace('OpenAPIServer\Model\\'); + +return [ + 'slimSettings' => [ + 'displayErrorDetails' => false, + 'logErrors' => true, + 'logErrorDetails' => true, + ], + + 'tokenAuthenticationOptions' => [ + /** + * Tokens are essentially passwords. You should treat them as such and you should always + * use HTTPS. If the middleware detects insecure usage over HTTP it will return unauthorized + * with a message Required HTTPS for token authentication. This rule is relaxed for requests + * on localhost. To allow insecure usage you must enable it manually by setting secure to + * false. + * Default: true + */ + // 'secure' => true, + + /** + * Alternatively you can list your development host to have relaxed security. + * Default: ['localhost', '127.0.0.1'] + */ + // 'relaxed' => ['localhost', '127.0.0.1'], + + /** + * By default on ocurred a fail on authentication, is sent a response on json format with a + * message (`Invalid Token` or `Not found Token`) and with the token (if found), with status + * `401 Unauthorized`. You can customize it by setting a callable function on error option. + * Default: null + */ + // 'error' => null, + ], + + 'mockerOptions' => [ + // 'dataMocker' => $mocker, + + // 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, array $responses) { + // // check if client clearly asks for mocked response + // $pingHeader = 'X-OpenAPIServer-Mock'; + // $pingHeaderCode = 'X-OpenAPIServer-Mock-Code'; + // if ( + // $request->hasHeader($pingHeader) + // && $request->getHeader($pingHeader)[0] === 'ping' + // ) { + // $responses = (array) $responses; + // $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default'; + // if (array_key_exists($requestedResponseCode, $responses)) { + // return $requestedResponseCode; + // } + + // // return first response key + // reset($responses); + // return key($responses); + // } + + // return false; + // }, + + // 'afterCallback' => function (ServerRequestInterface $request, ResponseInterface $response) { + // // mark mocked response to distinguish real and fake responses + // return $response->withHeader('X-OpenAPIServer-Mock', 'pong'); + // }, + ], +]; diff --git a/samples/server/petstore/php-slim4/config/prod/example.inc.php b/samples/server/petstore/php-slim4/config/prod/example.inc.php new file mode 100644 index 000000000000..0bbdd0810c86 --- /dev/null +++ b/samples/server/petstore/php-slim4/config/prod/example.inc.php @@ -0,0 +1,96 @@ +setModelsNamespace('OpenAPIServer\Model\\'); + +return [ + 'slimSettings' => [ + 'displayErrorDetails' => false, + 'logErrors' => true, + 'logErrorDetails' => true, + ], + + 'tokenAuthenticationOptions' => [ + /** + * Tokens are essentially passwords. You should treat them as such and you should always + * use HTTPS. If the middleware detects insecure usage over HTTP it will return unauthorized + * with a message Required HTTPS for token authentication. This rule is relaxed for requests + * on localhost. To allow insecure usage you must enable it manually by setting secure to + * false. + * Default: true + */ + // 'secure' => true, + + /** + * Alternatively you can list your development host to have relaxed security. + * Default: ['localhost', '127.0.0.1'] + */ + // 'relaxed' => ['localhost', '127.0.0.1'], + + /** + * By default on ocurred a fail on authentication, is sent a response on json format with a + * message (`Invalid Token` or `Not found Token`) and with the token (if found), with status + * `401 Unauthorized`. You can customize it by setting a callable function on error option. + * Default: null + */ + // 'error' => null, + ], + + 'mockerOptions' => [ + // 'dataMocker' => $mocker, + + // 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, array $responses) { + // // check if client clearly asks for mocked response + // $pingHeader = 'X-OpenAPIServer-Mock'; + // $pingHeaderCode = 'X-OpenAPIServer-Mock-Code'; + // if ( + // $request->hasHeader($pingHeader) + // && $request->getHeader($pingHeader)[0] === 'ping' + // ) { + // $responses = (array) $responses; + // $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default'; + // if (array_key_exists($requestedResponseCode, $responses)) { + // return $requestedResponseCode; + // } + + // // return first response key + // reset($responses); + // return key($responses); + // } + + // return false; + // }, + + // 'afterCallback' => function (ServerRequestInterface $request, ResponseInterface $response) { + // // mark mocked response to distinguish real and fake responses + // return $response->withHeader('X-OpenAPIServer-Mock', 'pong'); + // }, + ], +]; diff --git a/samples/server/petstore/php-slim4/index.php b/samples/server/petstore/php-slim4/index.php index f5295cedc9ac..c7b0a3a0a4bc 100644 --- a/samples/server/petstore/php-slim4/index.php +++ b/samples/server/petstore/php-slim4/index.php @@ -27,76 +27,15 @@ use Psr\Http\Message\ResponseInterface; use OpenAPIServer\Mock\OpenApiDataMocker; +// load config file $config = []; - -/** - * Token Middleware 1.x Options - * Options `header`, `regex`, `parameter`, `cookie`, `attribute`, `path`, `except`, `authenticator` - * are handled by SlimRouter class. These options are ignored by app and they omitted from current - * example. - * Ref: https://github.com/dyorg/slim-token-authentication/tree/1.x - */ -$config['tokenAuthenticationOptions'] = [ - /** - * Tokens are essentially passwords. You should treat them as such and you should always - * use HTTPS. If the middleware detects insecure usage over HTTP it will return unathorized - * with a message Required HTTPS for token authentication. This rule is relaxed for requests - * on localhost. To allow insecure usage you must enable it manually by setting secure to - * false. - * Default: true - */ - // 'secure' => true, - - /** - * Alternatively you can list your development host to have relaxed security. - * Default: ['localhost', '127.0.0.1'] - */ - // 'relaxed' => ['localhost', '127.0.0.1'], - - /** - * By default on ocurred a fail on authentication, is sent a response on json format with a - * message (`Invalid Token` or `Not found Token`) and with the token (if found), with status - * `401 Unauthorized`. You can customize it by setting a callable function on error option. - * Default: null - */ - // 'error' => null, -]; - -/** - * Mocker Middleware options. - */ -$mocker = new OpenApiDataMocker(); -$mocker->setModelsNamespace('OpenAPIServer\Model\\'); -$config['mockerOptions'] = [ - // 'dataMocker' => $mocker, - - // 'getMockStatusCodeCallback' => function (ServerRequestInterface $request, $responses) { - // // check if client clearly asks for mocked response - // $pingHeader = 'X-OpenAPIServer-Mock'; - // $pingHeaderCode = 'X-OpenAPIServer-Mock-Code'; - // if ( - // $request->hasHeader($pingHeader) - // && $request->getHeader($pingHeader)[0] === 'ping' - // ) { - // $responses = (array) $responses; - // $requestedResponseCode = ($request->hasHeader($pingHeaderCode)) ? $request->getHeader($pingHeaderCode)[0] : 'default'; - // if (array_key_exists($requestedResponseCode, $responses)) { - // return $requestedResponseCode; - // } - - // // return first response key - // reset($responses); - // return key($responses); - // } - - // return false; - // }, - - // 'afterCallback' => function ($request, $response) { - // // mark mocked response to distinguish real and fake responses - // return $response->withHeader('X-OpenAPIServer-Mock', 'pong'); - // }, -]; +if (is_array($prodConfig = @include(__DIR__ . '/config/prod/config.inc.php'))) { + $config = $prodConfig; +} elseif (is_array($devConfig = @include(__DIR__ . '/config/dev/config.inc.php'))) { + $config = $devConfig; +} else { + throw new InvalidArgumentException('Config file missed or broken.'); +} $router = new SlimRouter($config); $app = $router->getSlimApp(); @@ -118,6 +57,10 @@ * Note: This middleware should be added last. It will not handle any exceptions/errors * for middleware added after it. */ -$app->addErrorMiddleware(false, true, true); +$app->addErrorMiddleware( + $config['slimSettings']['displayErrorDetails'] ?? false, + $config['slimSettings']['logErrors'] ?? true, + $config['slimSettings']['logErrorDetails'] ?? true +); $app->run(); From d5a680e85fef7208106ebffa4c6493b86fc0725e Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Mon, 31 Aug 2020 03:46:55 +0200 Subject: [PATCH 11/11] [Extensions][Go][Java] Test x-auth-id-alias (#6642) Co-authored-by: Jim Schubert --- ...perimental-extensions-x-auth-id-alias.yaml | 6 + ...va-jersey2-extensions-x-auth-id-alias.yaml | 7 + ...erimental-extensions-x-auth-id-alias.yaml} | 0 .../resources/go-experimental/api.mustache | 19 +- .../go-petstore/api_fake_classname_tags123.go | 8 +- .../go-experimental/go-petstore/api_pet.go | 8 +- .../go-experimental/go-petstore/api_store.go | 8 +- .../go-experimental/.gitignore | 24 + .../go-experimental/.openapi-generator-ignore | 23 + .../go-experimental/.openapi-generator/FILES | 13 + .../.openapi-generator/VERSION | 1 + .../go-experimental/.travis.yml | 8 + .../x-auth-id-alias/go-experimental/README.md | 126 ++ .../go-experimental/api/openapi.yaml | 114 ++ .../go-experimental/api_usage.go | 490 +++++++ .../go-experimental/api_usage_test.go | 120 ++ .../x-auth-id-alias/go-experimental/client.go | 532 ++++++++ .../go-experimental/configuration.go | 262 ++++ .../go-experimental/docs/UsageApi.md | 256 ++++ .../go-experimental/git_push.sh | 58 + .../x-auth-id-alias/go-experimental/go.mod | 7 + .../x-auth-id-alias/go-experimental/go.sum | 15 + .../go-experimental/response.go | 46 + .../x-auth-id-alias/go-experimental/utils.go | 334 +++++ .../java/jersey2-java8/.gitignore | 21 + .../jersey2-java8/.openapi-generator-ignore | 23 + .../jersey2-java8/.openapi-generator/FILES | 33 + .../jersey2-java8/.openapi-generator/VERSION | 1 + .../java/jersey2-java8/.travis.yml | 22 + .../java/jersey2-java8/README.md | 155 +++ .../java/jersey2-java8/api/openapi.yaml | 119 ++ .../java/jersey2-java8/build.gradle | 125 ++ .../java/jersey2-java8/build.sbt | 26 + .../java/jersey2-java8/docs/UsageApi.md | 296 +++++ .../java/jersey2-java8/git_push.sh | 58 + .../java/jersey2-java8/gradle.properties | 2 + .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 99814 bytes .../gradle/wrapper/gradle-wrapper.properties | 5 + .../java/jersey2-java8/gradlew | 183 +++ .../java/jersey2-java8/gradlew.bat | 100 ++ .../java/jersey2-java8/pom.xml | 309 +++++ .../java/jersey2-java8/settings.gradle | 1 + .../src/main/AndroidManifest.xml | 3 + .../org/openapitools/client/ApiClient.java | 1149 +++++++++++++++++ .../org/openapitools/client/ApiException.java | 94 ++ .../org/openapitools/client/ApiResponse.java | 74 ++ .../openapitools/client/Configuration.java | 39 + .../client/CustomInstantDeserializer.java | 232 ++++ .../java/org/openapitools/client/JSON.java | 252 ++++ .../java/org/openapitools/client/Pair.java | 61 + .../client/RFC3339DateFormat.java | 55 + .../client/ServerConfiguration.java | 58 + .../openapitools/client/ServerVariable.java | 23 + .../org/openapitools/client/StringUtil.java | 83 ++ .../org/openapitools/client/api/UsageApi.java | 287 ++++ .../openapitools/client/auth/ApiKeyAuth.java | 79 ++ .../client/auth/Authentication.java | 33 + .../client/auth/HttpBasicAuth.java | 60 + .../client/auth/HttpBearerAuth.java | 62 + .../client/model/AbstractOpenApiSchema.java | 149 +++ .../openapitools/client/api/UsageApiTest.java | 91 ++ .../go-petstore/api_fake_classname_tags123.go | 8 +- .../go-experimental/go-petstore/api_pet.go | 8 +- .../go-experimental/go-petstore/api_store.go | 8 +- 64 files changed, 6844 insertions(+), 28 deletions(-) create mode 100644 bin/configs/go-experimental-extensions-x-auth-id-alias.yaml create mode 100644 bin/configs/java-jersey2-extensions-x-auth-id-alias.yaml rename bin/configs/{python-experimental-extensions-x-auth-alias.yaml => python-experimental-extensions-x-auth-id-alias.yaml} (100%) create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.gitignore create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator-ignore create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/FILES create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.travis.yml create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api/openapi.yaml create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage.go create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage_test.go create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/configuration.go create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageApi.md create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/git_push.sh create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.mod create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.sum create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/response.go create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/utils.go create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.gitignore create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator-ignore create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/FILES create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.travis.yml create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/README.md create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/api/openapi.yaml create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.gradle create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.sbt create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/docs/UsageApi.md create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/git_push.sh create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle.properties create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew.bat create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/pom.xml create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/settings.gradle create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/AndroidManifest.xml create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiException.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiResponse.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Configuration.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/CustomInstantDeserializer.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/JSON.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Pair.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerConfiguration.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerVariable.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/StringUtil.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/api/UsageApi.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/Authentication.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java create mode 100644 samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/test/java/org/openapitools/client/api/UsageApiTest.java diff --git a/bin/configs/go-experimental-extensions-x-auth-id-alias.yaml b/bin/configs/go-experimental-extensions-x-auth-id-alias.yaml new file mode 100644 index 000000000000..517b6fe83d78 --- /dev/null +++ b/bin/configs/go-experimental-extensions-x-auth-id-alias.yaml @@ -0,0 +1,6 @@ +generatorName: go-experimental +outputDir: samples/openapi3/client/extensions/x-auth-id-alias/go-experimental +inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml +templateDir: modules/openapi-generator/src/main/resources/go-experimental +additionalProperties: + packageName: x_auth_id_alias diff --git a/bin/configs/java-jersey2-extensions-x-auth-id-alias.yaml b/bin/configs/java-jersey2-extensions-x-auth-id-alias.yaml new file mode 100644 index 000000000000..8de24bd73e5f --- /dev/null +++ b/bin/configs/java-jersey2-extensions-x-auth-id-alias.yaml @@ -0,0 +1,7 @@ +generatorName: java +outputDir: samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8 +library: jersey2 +inputSpec: modules/openapi-generator/src/test/resources/3_0/extensions/x-auth-id-alias.yaml +additionalProperties: + artifactId: openapi3-extensions-x-auth-id-alias-jersey2-java8 + hideGenerationTimestamp: true diff --git a/bin/configs/python-experimental-extensions-x-auth-alias.yaml b/bin/configs/python-experimental-extensions-x-auth-id-alias.yaml similarity index 100% rename from bin/configs/python-experimental-extensions-x-auth-alias.yaml rename to bin/configs/python-experimental-extensions-x-auth-id-alias.yaml diff --git a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache index fb2553be562a..d887bddecc5b 100644 --- a/modules/openapi-generator/src/main/resources/go-experimental/api.mustache +++ b/modules/openapi-generator/src/main/resources/go-experimental/api.mustache @@ -252,13 +252,24 @@ func (r api{{operationId}}Request) Execute() ({{#returnType}}{{{.}}}, {{/returnT if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["{{#vendorExtensions.x-auth-id-alias}}{{.}}{{/vendorExtensions.x-auth-id-alias}}{{^vendorExtensions.x-auth-id-alias}}{{name}}{{/vendorExtensions.x-auth-id-alias}}"]; ok { + {{#vendorExtensions.x-auth-id-alias}} + if apiKey, ok := auth["{{.}}"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if prefix, ok := auth["{{name}}"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } + {{/vendorExtensions.x-auth-id-alias}} + {{^vendorExtensions.x-auth-id-alias}} + if apiKey, ok := auth["{{name}}"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + {{/vendorExtensions.x-auth-id-alias}} {{#isKeyInHeader}} localVarHeaderParams["{{keyParamName}}"] = key {{/isKeyInHeader}} diff --git a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index d126ee0bd33e..85275b451382 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -97,12 +97,12 @@ func (r apiTestClassnameRequest) Execute() (Client, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key_query"]; ok { + if apiKey, ok := auth["api_key_query"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarQueryParams.Add("api_key_query", key) } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/client/petstore/go-experimental/go-petstore/api_pet.go index 7bdcc03c6bff..65b9d66ad2b5 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_pet.go @@ -489,12 +489,12 @@ func (r apiGetPetByIdRequest) Execute() (Pet, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key } diff --git a/samples/client/petstore/go-experimental/go-petstore/api_store.go b/samples/client/petstore/go-experimental/go-petstore/api_store.go index 8d81867701cf..7780395b95bc 100644 --- a/samples/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/client/petstore/go-experimental/go-petstore/api_store.go @@ -176,12 +176,12 @@ func (r apiGetInventoryRequest) Execute() (map[string]int32, *_nethttp.Response, if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key } diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.gitignore b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.gitignore new file mode 100644 index 000000000000..daf913b1b347 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator-ignore b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/FILES b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/FILES new file mode 100644 index 000000000000..6ef83c13ad56 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/FILES @@ -0,0 +1,13 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +api_usage.go +client.go +configuration.go +docs/UsageApi.md +git_push.sh +go.mod +go.sum +response.go +utils.go diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION new file mode 100644 index 000000000000..d99e7162d01f --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.travis.yml b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.travis.yml new file mode 100644 index 000000000000..f5cb2ce9a5aa --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md new file mode 100644 index 000000000000..6d017a13cd40 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md @@ -0,0 +1,126 @@ +# Go API client for x_auth_id_alias + +This specification shows how to use x-auth-id-alias extension for API keys. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.GoClientExperimentalCodegen + +## Installation + +Install the following dependencies: + +```shell +go get github.com/stretchr/testify/assert +go get golang.org/x/oauth2 +go get golang.org/x/net/context +``` + +Put the package under your project folder and add the following in import: + +```golang +import sw "./x_auth_id_alias" +``` + +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. + +```golang +ctx := context.WithValue(context.Background(), sw.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identifield by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. + +``` +ctx := context.WithValue(context.Background(), sw.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), sw.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*UsageApi* | [**AnyKey**](docs/UsageApi.md#anykey) | **Get** /any | Use any API key +*UsageApi* | [**BothKeys**](docs/UsageApi.md#bothkeys) | **Get** /both | Use both API keys +*UsageApi* | [**KeyInHeader**](docs/UsageApi.md#keyinheader) | **Get** /header | Use API key in header +*UsageApi* | [**KeyInQuery**](docs/UsageApi.md#keyinquery) | **Get** /query | Use API key in query + + +## Documentation For Models + + + +## Documentation For Authorization + + + +### api_key + +- **Type**: API key +- **API key parameter name**: X-Api-Key +- **Location**: HTTP header + +Note, each API key must be added to a map of `map[string]APIKey` where the key is: X-Api-Key and passed in as the auth context for each request. + + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: URL query string + +Note, each API key must be added to a map of `map[string]APIKey` where the key is: api_key and passed in as the auth context for each request. + + +## Documentation for Utility Methods + +Due to the fact that model structure members are all pointers, this package contains +a number of utility functions to easily obtain pointers to values of basic types. +Each of these functions takes a value of the given basic type and returns a pointer to it: + +* `PtrBool` +* `PtrInt` +* `PtrInt32` +* `PtrInt64` +* `PtrFloat` +* `PtrFloat32` +* `PtrFloat64` +* `PtrString` +* `PtrTime` + +## Author + + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api/openapi.yaml b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api/openapi.yaml new file mode 100644 index 000000000000..a23135ce523d --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api/openapi.yaml @@ -0,0 +1,114 @@ +openapi: 3.0.0 +info: + description: This specification shows how to use x-auth-id-alias extension for API + keys. + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Extension x-auth-id-alias + version: 1.0.0 +servers: +- description: petstore server + url: http://{server}.swagger.io:{port}/v2 + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: https://localhost:8080/{version} + variables: + version: + default: v2 + enum: + - v1 + - v2 +tags: +- description: Show usage of x-auth-id-alias + name: usage +paths: + /both: + get: + description: Use both API keys + operationId: bothKeys + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + api_key: [] + summary: Use both API keys + tags: + - usage + /any: + get: + description: Use any API key + operationId: anyKey + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + - api_key: [] + summary: Use any API key + tags: + - usage + /query: + get: + description: Use API key in query + operationId: keyInQuery + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + summary: Use API key in query + tags: + - usage + /header: + get: + description: Use API key in header + operationId: keyInHeader + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key: [] + summary: Use API key in header + tags: + - usage +components: + schemas: {} + securitySchemes: + api_key: + in: header + name: X-Api-Key + type: apiKey + api_key_query: + in: query + name: api_key + type: apiKey + x-auth-id-alias: api_key diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage.go new file mode 100644 index 000000000000..7bd99eeb9731 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage.go @@ -0,0 +1,490 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + _context "context" + _ioutil "io/ioutil" + _nethttp "net/http" + _neturl "net/url" +) + +// Linger please +var ( + _ _context.Context +) + +// UsageApiService UsageApi service +type UsageApiService service + +type apiAnyKeyRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +AnyKey Use any API key +Use any API key + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiAnyKeyRequest +*/ +func (a *UsageApiService) AnyKey(ctx _context.Context) apiAnyKeyRequest { + return apiAnyKeyRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiAnyKeyRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.AnyKey") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/any" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["X-Api-Key"] = key + } + } + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if prefix, ok := auth["api_key_query"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarQueryParams.Add("api_key", key) + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} +type apiBothKeysRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +BothKeys Use both API keys +Use both API keys + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiBothKeysRequest +*/ +func (a *UsageApiService) BothKeys(ctx _context.Context) apiBothKeysRequest { + return apiBothKeysRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiBothKeysRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.BothKeys") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/both" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["X-Api-Key"] = key + } + } + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if prefix, ok := auth["api_key_query"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarQueryParams.Add("api_key", key) + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} +type apiKeyInHeaderRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +KeyInHeader Use API key in header +Use API key in header + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiKeyInHeaderRequest +*/ +func (a *UsageApiService) KeyInHeader(ctx _context.Context) apiKeyInHeaderRequest { + return apiKeyInHeaderRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiKeyInHeaderRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.KeyInHeader") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/header" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["X-Api-Key"] = key + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} +type apiKeyInQueryRequest struct { + ctx _context.Context + apiService *UsageApiService +} + +/* +KeyInQuery Use API key in query +Use API key in query + * @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +@return apiKeyInQueryRequest +*/ +func (a *UsageApiService) KeyInQuery(ctx _context.Context) apiKeyInQueryRequest { + return apiKeyInQueryRequest{ + apiService: a, + ctx: ctx, + } +} + +/* +Execute executes the request +@return map[string]interface{} +*/ +func (r apiKeyInQueryRequest) Execute() (map[string]interface{}, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodGet + localVarPostBody interface{} + localVarFormFileName string + localVarFileName string + localVarFileBytes []byte + localVarReturnValue map[string]interface{} + ) + + localBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, "UsageApiService.KeyInQuery") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/query" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["api_key"]; ok { + var key string + if prefix, ok := auth["api_key_query"]; ok && prefix.Prefix != "" { + key = prefix.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarQueryParams.Add("api_key", key) + } + } + } + req, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := r.apiService.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage_test.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage_test.go new file mode 100644 index 000000000000..5cd1dd678357 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/api_usage_test.go @@ -0,0 +1,120 @@ +package x_auth_id_alias + +import ( + "bytes" + "context" + "fmt" + "io/ioutil" + "net/http" + "testing" +) + +// RoundTripFunc . +type RoundTripFunc func(req *http.Request) *http.Response + +// RoundTrip calls f on given request. +func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { + return f(req), nil +} + +//NewTestClient returns *http.Client with replaced Transport layer. +func NewTestClient(fn RoundTripFunc) *http.Client { + return &http.Client{ + Transport: RoundTripFunc(fn), + } +} + +type APIRequest interface { + Execute() (map[string]interface{}, *http.Response, error) +} + +func TestAPIKeys(t *testing.T) { + ctx := context.WithValue( + context.Background(), + ContextAPIKeys, + map[string]APIKey{ + "api_key": { + Key: "SECRET_VALUE", + Prefix: "PREFIX", + }, + }, + ) + configuration := NewConfiguration() + apiClient := NewAPIClient(configuration) + + testCases := map[string]struct { + Check func(t *testing.T, req *http.Request) + Request APIRequest + }{ + "AnyKey": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "PREFIX SECRET_VALUE" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "PREFIX SECRET_VALUE") + } + values := req.URL.Query() + if values.Get("api_key") != "SECRET_VALUE" { + t.Fatalf("%s != %s", values.Get("api_key"), "SECRET_VALUE") + } + }, + Request: apiClient.UsageApi.AnyKey(ctx), + }, + "BothKeys": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "PREFIX SECRET_VALUE" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "PREFIX SECRET_VALUE") + } + values := req.URL.Query() + if values.Get("api_key") != "SECRET_VALUE" { + t.Fatalf("%s != %s", values.Get("api_key"), "SECRET_VALUE") + } + }, + Request: apiClient.UsageApi.BothKeys(ctx), + }, + "KeyInHeader": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "PREFIX SECRET_VALUE" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "PREFIX SECRET_VALUE") + } + values := req.URL.Query() + if values.Get("api_key") != "" { + t.Fatalf("%s != %s", values.Get("api_key"), "") + } + }, + Request: apiClient.UsageApi.KeyInHeader(ctx), + }, + "KeyInQuery": { + Check: func(t *testing.T, req *http.Request) { + if req.Header.Get("X-Api-Key") != "" { + t.Fatalf("%s != %s", req.Header.Get("X-Api-Key"), "") + } + values := req.URL.Query() + if values.Get("api_key") != "SECRET_VALUE" { + t.Fatalf("%s != %s", values.Get("api_key"), "SECRET_VALUE") + } + }, + Request: apiClient.UsageApi.KeyInQuery(ctx), + }, + } + + for name, tc := range testCases { + t.Run(name, func(t *testing.T) { + configuration.HTTPClient = NewTestClient(func(req *http.Request) *http.Response { + tc.Check(t, req) + return &http.Response{ + StatusCode: 200, + Body: ioutil.NopCloser(bytes.NewBufferString("")), + Header: make(http.Header), + } + }) + _, httpresp, err := tc.Request.Execute() + if httpresp.StatusCode != 200 { + fmt.Printf("%v != 200", httpresp.StatusCode) + t.FailNow() + } + if err != nil { + fmt.Printf("%v, error: %v", httpresp.Body, err) + t.FailNow() + } + }) + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go new file mode 100644 index 000000000000..30335de6c297 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go @@ -0,0 +1,532 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "log" + "mime/multipart" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" +) + +var ( + jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) + xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) +) + +// APIClient manages communication with the OpenAPI Extension x-auth-id-alias API v1.0.0 +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + UsageApi *UsageApiService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.UsageApi = (*UsageApiService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } else if t, ok := obj.(time.Time); ok { + return t.Format(time.RFC3339) + } + + return fmt.Sprintf("%v", obj) +} + +// helper for converting interface{} parameters to json strings +func parameterToJson(obj interface{}) (string, error) { + jsonBuf, err := json.Marshal(obj) + if err != nil { + return "", err + } + return string(jsonBuf), err +} + + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + if c.cfg.Debug { + dump, err := httputil.DumpRequestOut(request, true) + if err != nil { + return nil, err + } + log.Printf("\n%s\n", string(dump)) + } + + resp, err := c.cfg.HTTPClient.Do(request) + if err != nil { + return resp, err + } + + if c.cfg.Debug { + dump, err := httputil.DumpResponse(resp, true) + if err != nil { + return resp, err + } + log.Printf("\n%s\n", string(dump)) + } + return resp, err +} + +// Allow modification of underlying config for alternate implementations and testing +// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior +func (c *APIClient) GetConfig() *Configuration { + return c.cfg +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + formFileName string, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form parameters and file if available. + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile(formFileName, filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + } + + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Override request host, if applicable + if c.cfg.Host != "" { + url.Host = c.cfg.Host + } + + // Override request scheme, if applicable + if c.cfg.Scheme != "" { + url.Scheme = c.cfg.Scheme + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if len(b) == 0 { + return nil + } + if s, ok := v.(*string); ok { + *s = string(b) + return nil + } + if xmlCheck.MatchString(contentType) { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } + if jsonCheck.MatchString(contentType) { + if actualObj, ok := v.(interface{GetActualInstance() interface{}}); ok { // oneOf, anyOf schemas + if unmarshalObj, ok := actualObj.(interface{UnmarshalJSON([]byte) error}); ok { // make sure it has UnmarshalJSON defined + if err = unmarshalObj.UnmarshalJSON(b); err!= nil { + return err + } + } else { + errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") + } + } else if err = json.Unmarshal(b, v); err != nil { // simple model + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + err = xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } else { + expires = now.Add(lifetime) + } + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericOpenAPIError Provides access to the body, error and model on returned errors. +type GenericOpenAPIError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericOpenAPIError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericOpenAPIError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericOpenAPIError) Model() interface{} { + return e.model +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/configuration.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/configuration.go new file mode 100644 index 000000000000..425e8f19c156 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/configuration.go @@ -0,0 +1,262 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "context" + "fmt" + "net/http" + "strings" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes an oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextBasicAuth takes BasicAuth as authentication for the request. + ContextBasicAuth = contextKey("basic") + + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + + // ContextAPIKeys takes a string apikey as authentication for the request + ContextAPIKeys = contextKey("apiKeys") + + // ContextHttpSignatureAuth takes HttpSignatureAuth as authentication for the request. + ContextHttpSignatureAuth = contextKey("httpsignature") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client +type Configuration struct { + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client +} + +// NewConfiguration returns a new Configuration object +func NewConfiguration() *Configuration { + cfg := &Configuration{ + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "http://{server}.swagger.io:{port}/v2", + Description: "petstore server", + Variables: map[string]ServerVariable{ + "server": ServerVariable{ + Description: "No description provided", + DefaultValue: "petstore", + EnumValues: []string{ + "petstore", + "qa-petstore", + "dev-petstore", + }, + }, + "port": ServerVariable{ + Description: "No description provided", + DefaultValue: "80", + EnumValues: []string{ + "80", + "8080", + }, + }, + }, + }, + { + URL: "https://localhost:8080/{version}", + Description: "The local server", + Variables: map[string]ServerVariable{ + "version": ServerVariable{ + Description: "No description provided", + DefaultValue: "v2", + EnumValues: []string{ + "v1", + "v2", + }, + }, + }, + }, + }, + OperationServers: map[string]ServerConfigurations{ + }, + } + return cfg +} + +// AddDefaultHeader adds a new HTTP header to the default header in the request +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("Index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("The variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageApi.md b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageApi.md new file mode 100644 index 000000000000..eb6a220249cd --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageApi.md @@ -0,0 +1,256 @@ +# \UsageApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AnyKey**](UsageApi.md#AnyKey) | **Get** /any | Use any API key +[**BothKeys**](UsageApi.md#BothKeys) | **Get** /both | Use both API keys +[**KeyInHeader**](UsageApi.md#KeyInHeader) | **Get** /header | Use API key in header +[**KeyInQuery**](UsageApi.md#KeyInQuery) | **Get** /query | Use API key in query + + + +## AnyKey + +> map[string]interface{} AnyKey(ctx).Execute() + +Use any API key + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.AnyKey(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.AnyKey``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `AnyKey`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.AnyKey`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiAnyKeyRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## BothKeys + +> map[string]interface{} BothKeys(ctx).Execute() + +Use both API keys + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.BothKeys(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.BothKeys``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `BothKeys`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.BothKeys`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiBothKeysRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## KeyInHeader + +> map[string]interface{} KeyInHeader(ctx).Execute() + +Use API key in header + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.KeyInHeader(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.KeyInHeader``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `KeyInHeader`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.KeyInHeader`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiKeyInHeaderRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## KeyInQuery + +> map[string]interface{} KeyInQuery(ctx).Execute() + +Use API key in query + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.UsageApi.KeyInQuery(context.Background(), ).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageApi.KeyInQuery``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `KeyInQuery`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageApi.KeyInQuery`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiKeyInQueryRequest struct via the builder pattern + + +### Return type + +**map[string]interface{}** + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/git_push.sh b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.mod b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.mod new file mode 100644 index 000000000000..f9811556cc5a --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.mod @@ -0,0 +1,7 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.13 + +require ( + golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 +) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.sum b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.sum new file mode 100644 index 000000000000..ce55b3c6a08f --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/go.sum @@ -0,0 +1,15 @@ +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/antihax/optional v1.0.0 h1:xK2lYat7ZLaVVcIuj82J8kIro4V6kDe0AUDFboUCwcg= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/response.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/response.go new file mode 100644 index 000000000000..f5aa518c3c5d --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/response.go @@ -0,0 +1,46 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResonse object. +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/utils.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/utils.go new file mode 100644 index 000000000000..c6930485543b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/utils.go @@ -0,0 +1,334 @@ +/* + * OpenAPI Extension x-auth-id-alias + * + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package x_auth_id_alias + +import ( + "encoding/json" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given integer value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return v.value.MarshalJSON() +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.gitignore b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.gitignore new file mode 100644 index 000000000000..a530464afa1b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator-ignore b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/FILES b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/FILES new file mode 100644 index 000000000000..d26aa67445a2 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/FILES @@ -0,0 +1,33 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/UsageApi.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/ApiException.java +src/main/java/org/openapitools/client/ApiResponse.java +src/main/java/org/openapitools/client/Configuration.java +src/main/java/org/openapitools/client/CustomInstantDeserializer.java +src/main/java/org/openapitools/client/JSON.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/RFC3339DateFormat.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/UsageApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION new file mode 100644 index 000000000000..d99e7162d01f --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.travis.yml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.travis.yml new file mode 100644 index 000000000000..e3bdf2af1bea --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/README.md new file mode 100644 index 000000000000..7bf2775d7a8c --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/README.md @@ -0,0 +1,155 @@ +# openapi3-extensions-x-auth-id-alias-jersey2-java8 + +OpenAPI Extension x-auth-id-alias + +- API version: 1.0.0 + +This specification shows how to use x-auth-id-alias extension for API keys. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.7+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + openapi3-extensions-x-auth-id-alias-jersey2-java8 + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "org.openapitools:openapi3-extensions-x-auth-id-alias-jersey2-java8:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/openapi3-extensions-x-auth-id-alias-jersey2-java8-1.0.0.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import org.openapitools.client.*; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class UsageApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.anyKey(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#anyKey"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*UsageApi* | [**anyKey**](docs/UsageApi.md#anyKey) | **GET** /any | Use any API key +*UsageApi* | [**bothKeys**](docs/UsageApi.md#bothKeys) | **GET** /both | Use both API keys +*UsageApi* | [**keyInHeader**](docs/UsageApi.md#keyInHeader) | **GET** /header | Use API key in header +*UsageApi* | [**keyInQuery**](docs/UsageApi.md#keyInQuery) | **GET** /query | Use API key in query + + +## Documentation for Models + + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + + +- **Type**: API key +- **API key parameter name**: X-Api-Key +- **Location**: HTTP header + +### api_key_query + + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: URL query string + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/api/openapi.yaml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/api/openapi.yaml new file mode 100644 index 000000000000..1ea9d4a67836 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/api/openapi.yaml @@ -0,0 +1,119 @@ +openapi: 3.0.0 +info: + description: This specification shows how to use x-auth-id-alias extension for API + keys. + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Extension x-auth-id-alias + version: 1.0.0 +servers: +- description: petstore server + url: http://{server}.swagger.io:{port}/v2 + variables: + server: + default: petstore + enum: + - petstore + - qa-petstore + - dev-petstore + port: + default: "80" + enum: + - "80" + - "8080" +- description: The local server + url: https://localhost:8080/{version} + variables: + version: + default: v2 + enum: + - v1 + - v2 +tags: +- description: Show usage of x-auth-id-alias + name: usage +paths: + /both: + get: + description: Use both API keys + operationId: bothKeys + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + api_key: [] + summary: Use both API keys + tags: + - usage + x-accepts: application/json + /any: + get: + description: Use any API key + operationId: anyKey + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + - api_key: [] + summary: Use any API key + tags: + - usage + x-accepts: application/json + /query: + get: + description: Use API key in query + operationId: keyInQuery + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key_query: [] + summary: Use API key in query + tags: + - usage + x-accepts: application/json + /header: + get: + description: Use API key in header + operationId: keyInHeader + responses: + "200": + content: + application/json: + schema: + type: object + description: successful operation + security: + - api_key: [] + summary: Use API key in header + tags: + - usage + x-accepts: application/json +components: + schemas: {} + securitySchemes: + api_key: + in: header + name: X-Api-Key + type: apiKey + api_key_query: + in: query + name: api_key + type: apiKey + x-auth-id-alias: api_key + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.gradle b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.gradle new file mode 100644 index 000000000000..dcebf9606eef --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.gradle @@ -0,0 +1,125 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = '1.0.0' + +buildscript { + repositories { + maven { url "https://repo1.maven.org/maven2" } + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided 'javax.annotation:jsr250-api:1.0' + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'openapi3-extensions-x-auth-id-alias-jersey2-java8' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.22" + jackson_version = "2.10.3" + jackson_databind_version = "2.10.4" + jackson_databind_nullable_version = "0.2.1" + jersey_version = "2.27" + junit_version = "4.13" + threetenbp_version = "2.9.10" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.google.code.findbugs:jsr305:3.0.2" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.inject:jersey-hk2:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-json-jackson:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version" + compile "com.brsanthu:migbase64:2.2" + compile 'javax.annotation:javax.annotation-api:1.3.2' + testCompile "junit:junit:$junit_version" +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.sbt b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.sbt new file mode 100644 index 000000000000..358d6dc183a0 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/build.sbt @@ -0,0 +1,26 @@ +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "openapi3-extensions-x-auth-id-alias-jersey2-java8", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.22", + "org.glassfish.jersey.core" % "jersey-client" % "2.27", + "org.glassfish.jersey.inject" % "jersey-hk2" % "2.27", + "org.glassfish.jersey.media" % "jersey-media-multipart" % "2.27", + "org.glassfish.jersey.media" % "jersey-media-json-jackson" % "2.27", + "com.fasterxml.jackson.core" % "jackson-core" % "2.10.4" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.10.4" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.4" % "compile", + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile", + "com.brsanthu" % "migbase64" % "2.2", + "javax.annotation" % "javax.annotation-api" % "1.3.2" % "compile", + "junit" % "junit" % "4.13" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/docs/UsageApi.md b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/docs/UsageApi.md new file mode 100644 index 000000000000..7af13f24d178 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/docs/UsageApi.md @@ -0,0 +1,296 @@ +# UsageApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**anyKey**](UsageApi.md#anyKey) | **GET** /any | Use any API key +[**bothKeys**](UsageApi.md#bothKeys) | **GET** /both | Use both API keys +[**keyInHeader**](UsageApi.md#keyInHeader) | **GET** /header | Use API key in header +[**keyInQuery**](UsageApi.md#keyInQuery) | **GET** /query | Use API key in query + + + +## anyKey + +> Object anyKey() + +Use any API key + +Use any API key + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.anyKey(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#anyKey"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## bothKeys + +> Object bothKeys() + +Use both API keys + +Use both API keys + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.bothKeys(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#bothKeys"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## keyInHeader + +> Object keyInHeader() + +Use API key in header + +Use API key in header + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.keyInHeader(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#keyInHeader"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## keyInQuery + +> Object keyInQuery() + +Use API key in query + +Use API key in query + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.UsageApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure API key authorization: api_key_query + ApiKeyAuth api_key_query = (ApiKeyAuth) defaultClient.getAuthentication("api_key_query"); + api_key_query.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key_query.setApiKeyPrefix("Token"); + + UsageApi apiInstance = new UsageApi(defaultClient); + try { + Object result = apiInstance.keyInQuery(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UsageApi#keyInQuery"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Object** + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/git_push.sh b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/git_push.sh new file mode 100644 index 000000000000..ced3be2b0c7b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle.properties b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle.properties new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..e35d600ab118c93d7e23084511e366fb638b1225 GIT binary patch literal 99814 zcma&PhnHnlwJv@t=bUrSIp>^n&UGs1oO3`_5J6C)fQV#4P=at(crZqH6Psi=P3S<2 z-s{!tz1}y*@BIPq`}SPDPc`WMy)nKS)?E9nz1B?oRMn}f)&>hpdxOE&)?hG{feZ$7 zjT;PhkWE#cWl43-)hQN+*6S`@{O>pZS8-7(E-3+dp1icFthuhbs-rWxsTvnGfq=$_ zq+|%EhNO5geDqR#Dzpq42~UEk1MxKpb%|#7kP{%FKMu?%N(NlQC(7Fs!W*l;|3X>@j}V`Fq}V{$DrEqQ!lbbTE!ZU-%aNs7SxPYry+Aj=Js?_wL zx?A??)6By{5Wv)qSP-3S71LKV(hZKFB3^jh0wxF=vw>m`O2|oW)y*uk@+f@>g|*=X za!&%=e)D&{N%m}^7es$LSRM~?5)s@VaP9>I&w2583r;g)IToSwo!pRW8B~ebI)V&1 zb00W;(HiBl0{X**h8!ghDbE7r2qG-(rc<4ukY~a@r4Ll|KfQrmlh8uD6cbk zq(J3WB*xDw$&8@@cy5-}(iYeh2$=it=dJ}_46HRqjR84-AFnj|x&WiPx-oFU7cc3m zF$Zd~3{90@S8eb}rz@=Nd@5uzHEP^nH1IM|YQ$)FHS=nMzTD@1z21He+|^sNbge=U zDQ{MpwPM83#=Si~95QS?FemEZ^IL`vBFh{`S#s~)3Kr^|JX!~NWTsjM^hs;hStbbJ z4w>?RpNNf)?PjKgJ1Bv>0lGj`DgX7Qd%$^5fH@XBDmt5mm#E7Ig z!^o;#hyV-SPmY0b=K+?wRUVvwpb0}AJhIb(49#Oy#MuM@#&#soZZ5+gRKoFHcIW3K1y-8}Ay0nEM` zEC>X2=dP=0^S-=|qX!Q><_RWndhcdkPlqSV=tX+l>Ak1H1qJqy<2(Rg;duboqV|3WJsHH9 z0G&be;1+Re<%|O!IG)+sPU^CvQyVnS3->^*m99TO`a16cj0Eu{{>;WsM>B9O{$G9T zMyLYbc|jkAKw~Zf3Gs9^TgNd&)awKWP_OQfqz{ZBmPAW5*f-I=e9~6kqmRaupfbn+ zGj)}Vy!9Yheiv9L$RuP?5Wy2SZ^;Op!@b(bftZc?A~8;ih<=j`U3Y6PpX(3CY+YCf zbH98KxPWP>miY8Bx{V9*In4Mmc1+BCM)_2)aObDo3jw9#it!rK1DddP>=qo9RWtQ7&Wz$dRXI9_6gM zMnM4Voj`<>+vUf7N|SO|3o03meP(;A6;p^C6>uK{7YJ^?iK_(UG6{63G?#G~*8vLZ z!1%0V_5)0Ss53wP<4xa@F?i*cTE_3oCppw7piJw7-2=u1SlI!y7CnNw1aM2HTnG@O za9-KP%wdZRFp5!lDNh-62&P`^#fo?HZKc~-nz5icP$`HTPcx5KZo`1#TeY5!D_nzO z%>-aaF}Qg6niX0?BiVALiOa9&wm@1;fC1Z#6!5h#xn}s@ft$fwGT{;b_{~}6^7hig z^6131FLU^sCf+~Q6%3fk0*l{b!Z?7GuS%en57K#`-vs6k0y_6|e0X}MQ=FLSC?^IQ z7!pC(`&V$G)X>Q3{dKYW^m7qbp6?honjsaqttFDSczC#5KiWdwLvgPnf@tWPD_Y%K<%8(>SlmOc+6lP>l>3xlWY20 zVWwY4K$j;3u#l~}yS;0AI5Wo z-uRE(9s;K)Gt{e@d2io#4F0Fz-Ukjam>Z4JGAI&plK1HY1A8pcD5AWme}y|Pi%VCp z-pplvB@Qi=nnV8iwObrCFQ-;JPB_6Z!Bz-FfTlpj(QAz2A0Pcz8c*T~%BW-o4tf_? zm|6)8Km(|jCp#Eb-7I~IujUTiCWCDufPx^t9vBpH_I0*P=A0k_VnrWW4Kou}>h98G zywch+QQe#oV3SNA)n@DaxUDR|| z6HuRSs1S{Tm;tTFk^3y=iTSY}DM!p=R~{N5#~~l=B9S$XMs~lUKgQb@5imhhp2`sn!xpt?E*;XA!Irw{%Y~=%(m2S{UX>LI72u6rKn#u` zvtdt^ojI$-3$H?N1ugsa*AG<7gm5lkFDk~-+b6)U6I>G3Ji_N^e( z&fm|&cz}WeBh*Z=a~;NZhhEXYzdZ<=fKlnN(}zrR?xlrJ;(6#tbyxF{Pz<`6S~0Ek z@^m~{$|pY_UNr@zh1)Dh2eXI(WA{=K$a06CNp}HnJ`ScLHo-bL`;1J0zxz0Y)v5OA z!0lMScPm?B{}7L)qrP8P2ZjQhxJ=)huXkmtrmIhik_=JYr*fE??j5dQvC9Mkc14sy zq;nHi*MAf2qnGWAeej+7M!X}){Qr5Eg@^ynZrSF>%;eI>?D*)$vgz^Pft8os%RGx9 zTiJBzr7jT9Gdcjq&;v*87HPAo(a}tkPBH47IlHh8mRh@;0Ac6abYKX9vNPR~Fl&lw z2J@B&E}(}_!Vvt&r@z~m*eAA$F<#`QdZpO<{UP`EWxz=E*MhN-m>j|MChrJDQD<(X zMJBWvQwPNg&g{u6WS$k3*fL*v4u5t89lM?^Rp9EAmv0ws4)x^2#j@daEK!{WHW;RRruVfc@dbe!3KP`$yAUS3i5RgN=;1OncE=OKw+T6L4R-> z*oj##?O!nhyv_*mk5_&%FxP3u0Q2fw+}7pKvl|3&txIry2Z` z>zjf)49mdTVDJbw7{dPN)}VhG&}X+Z*rOW!)UH|w%ZxKcKEEY{Dx>dT02Xxi77qv= zJWVh23&?FbcNbG-hLPSKALxT91$oafGJ;ZDSC#O&tf@xN)Qz+xBeZg#dhm1qYeTLB zXZ(O|MqFSEF~?m2Ouy+8(bb+^SYRwk!Hhv|XqT96{5N5nicf!V9N$IwxQ=~9^0 zz85W^n~rS?u;I&_F~h||V!=u}sab(p4d;LZyn!2thpRKNKLUnguoAXfraN_B?Zc;D zh_XPXSDD_M2A*$#v%GV+({WGJ;_))n5FS<)CbZ*hFu*`Le9(H#v?TGiNgy53(0Cr+ ztVFlQL)$hT4x{}!uw^z3KqWaeZ9e{0hM1lj1SLJ?lB?P?yRPBNBJjHYxP~g6` z2EmpMy!(O?{36wfw_XPS`wb6)=Ys${h6r#86uBMk&AkqXy177DmKm3aWkTnl-!E$H zrN`WPi^`L6y4)ZiNZ?-|ze|))Z|xk1Ry5a=3t^bHXwLU&iLx@K z4BM7ECeO?>8I^=!3eNSPy7A3lGBFl{UFk8PdS>Eqn-3xS#G`_b9iRxb!i1u$x5mKK z#6DDjt`>a!g9a##9vuz+x(!PImEVkVpUN=|_DPIlkQoPd@yGLYRl!^f6FIHMey(r5 zX%}i8NQX+^jvyPD>}uwjPHvOT%CTZ*%{1uU-+)b&sq%oH2m+KJP3t*T$prY{9=~f# z29xJ+vEo?;eC)9o?Z5StatP*F1qf*CO6wABrX`(e3dDluFW)^MBSY{4^=`wDM+8zm z2Gwr#OP~yJh>HP(n$WW>kB;D_oDR%I8e+SkFYU69{l6&6#?cwBX7Ia{M*IoIc zbH!2y;~qAk(!!daX#zZ7a*h{OgBiL}8@beZ%WhnmmlkbA(#(e&=C8U5^8B{O2ck&+|(@{{*+~1DpMuRq?xkLSSozK+h?x)o z+VKE$QLo&M3Bm}-Ob2rW*?~qG-zJcNuL8={rMA$cgF?XLWnzVH4ZHaBMTp#ex++O| z0IDjm&V1;tW?>k z2R2viBqMO1d&UdQzO)CNZV~uGH0}omywm@2LCib%q`A zaw*d7P|p4wjGp2RJ^%V^wNTa25|as_BPLu$7tZYib`$IhD~@1SUmV{J7HgXbaP3>) zGqJR<=PS$C6Wj+h1Zs-ni+e(ucGi6P#utx+CzX^JwX-<@U)}rzQNV*hnXCiA zO2p}#As4QGmmA>>ld3EdECcj46kxm$@;GT%`+{jzIaQzKP6d0W0u#gH+7^!(JJAik z8p@W$qU33Sc@bmk2pDk^V6A;|%lkL3&;b{pF}X9+q^hdz=rzh~!1F+XpWYzjT@m|q zGlL!0K9e>eHU@OV8;tu2tM*dq?TJzH-=BLP;*&>UV4p=2b@KKvs%A=Vok;?5Zqh|sGbQ1nES+6isoRY z4x3*YwlWeb#$1S9^HMLq$*`^iqZbdjDo`W>oH6E>0p(^o18{LDwh*l%Fa*j#iJDLa z!Irsr{)apiP?I@MFENZWrym2SJN!U6c(YAc%<$?6L-R%=-3>$Y8G-GC$vCqZN{Y1FSYb|30@R_~Is!6_H`&r&Q5&YNhtrrr1rd`(kK9?WqPv{#8|b=sFfIZ zpaAsVZ$gnzyVPq&H(?P(LGb8d z!(g*w6CM@;8NjDO;F4I9=)Z<38GzFqETcA+7<9e^C=X-<>gg$Rg5Z7u*1^8084#`@ z-XGvFlV{uXr+574ySureZJI&A^df^`zaS&JF0Oabevm;|ZpxglVSuJbOc6O#6+d=8$7P-2>+X9k11_E|O+R#I4D>O}eH#MkUEEnW9 zREQ#+{@q|=+j|-v516LFh38coKz9t}Y;zUZ1{rUN)Fi;zxcHaNuwsnk8-K-AGGenU6?S=1yJ9&TsDw|{g?#>&lb7rApV$!CeeOeUH6+RJd1o74!Sc$L7HW9Z^A|aP1^e zEvRz|EZP9}(c>}TI-(dlW*L`cq$oE*Y)u0LV03ltzJLCD?uC1y0%xBU$qb4IwJ~c# zCd^AJFFiaOa43`D3w>m94r^QB6ToH&@UCGW-UeQht$b=7AX9-Nz*z>s z<|vp$aWn7oHT?Om*R;*@3xt`AEc^#)8nYdQ$wJWeKM!L9(H(&Pk;JtB`6puk z_=9rH5P%K6)RVzY0L^(ZX#g5ZFWpOFTg6(eV}<|`8ROssAeM%JZxgndWI&z>;g%-{ z(3t>do=IMd5_>(D0h+w+-u@0`q7029z*SS4zxwd7ErzXKe715rgOL=}K)8#lZpYjk z0!8zpjd1O^ig=Jorm;6jRpZ$Qq2~^&{A&o^`1tm~a-U`xf%(tB1#Wh|^TYBExDRXX z6N`=pL&iULeAUkQ!shzy)@1eU!erU_I6kD|yHxJ$?{D+}6ckY#uO` zxfUk#wQZdYF0U}pdVKuoncFBx}0ln=zp0K9c%2i(Px=VazY za;PH}T7aY0xelTF`O*L+FpyD=MKW3!apet>!cFBIVoG93+NNtCrt%%U_9;EwwCtQgACq$S4*STh&V0PHa@>+d)qU z9ms{HTq23pw+LDT&CNFNK>!SX5r{5gWZ9Y+C0~$F;@rEpLjni9FXsixyL{HDyFoL8 zdSz--M0r_vya!ZPInzz>!409z3-0govtn{->ALzNR4Y(iXHiT3(bhY^UR0~>8$Y>= zyO{tn)&KP#UYf*>urtyOFyufOhzh@k|WryDO)(px%0n_TRbFNV@p>$Ovn9L%Q+1$;vSFm34_ z76hMK44;lwW?YIRn0pUfN`Z11)WZyO76IU~CQ^7ugh+fOpvx z3%J@Dy(UoISWU4ls6GUZDRL6-rgdNrtJCL-pp~gGL-p1te*aSk)+eL0+sF-VGOU0z z)2M4u2H@IvjzU+UaSM!j^M@}7Ze>9^iG$@lp5V(@*FJknWj%(bhSas7V)g#d_CG01`hh{QB~$P^8%9;l|YouZS0V){H<^s*ewJ^Gxf)|^!; z#!gjrsz-@&PXztV-10dDQ};E7gr0i|Lkn%fwuJs;kK0%s2>gdq5DysfljFAc& zG;fv;a1>-r_{)!bd`6ZWf=*l$8MZ#Ip>K0rH$QI!baa~ea=PkvQ3FRtA4d9ZMZIzYVE5-Unt`Bhs)MNpseMexe;yaJiO`9MT(_F6tb`{t1F2*y>kq;Jpd*h(70yQB^Vaj= ztIQYyuX1uc{~!b#Ht_j(+rWKz4g;tJWVe?U$D0AG&Z=XrSGF>=%pp56pc<5S?t9?e zr(lz};@Op7xLd${w&|VkZSAqVYn#L*+~j8mF+`S(L5W)eW51#EBIB3-ZnM>To=cu9Llhps@j|tRhe-or@eR8dKd2zCFd3kOOyte#O0>|P_K;e)&wR9F?=r=}v_eguZ$3%Ak< zwTEC8AOTO-5Xwe1I;9(-g?5>Kdo zn+P(iNVU@uxoWw~*PRc-1W*)+i|~3ux~}o^0nnEZTszW!FTEpZXM($eV&=S)dWNAa zn2xaQ?M%n5rLyW1targjKKpJwdjjAkBK^z*P*}G|*M6@yb+u(yB};v`9rG6maUTL_ z@#U%3!K?we89oLC+Yt1-!QYfK7_uWV;k0kMU;M?6OFGXj7*RXXG7TpBHAtT|T=-p9 zx%PRTkTl&W3KOPe)EE4!)=H;%bASh2QhCN^V!t{=r?BvcxLXb~uBy8;Q75v&fYaXt z3z(~F3=HT>+vtcc#xRMEdwo2~4Fceo1OT1FW!jvZ#Bk^ktF~tlLj;8C!)A`{7>wA0 z{q4awEI+tmRxSx#6bas%!XUQExTlF#2JjU?fvSoG>o~hMrr~s9rOYsaMri2)MK!ud zA2``SW4=(F`ko3E69ZtL0XZvXQFPT-Q&gTb2SN#LJlh+_(JYE_@x5V)zQ(<;> zE1{+4;VT#bwKhD)n99D~qUNYKAHR4DOdbV6?F^4sC>WogCsCnVIC~Xv{vOr#PF|D4 zHR)8pV3rM#U|@x7jS6xsL#*X*z9h;*-sR_@<;BOda?C+ppljbJw|UGT{VOCCR#eQi(6d$VDt8y^yxS+Xh2eQ63ECGofyF7XkN{@Q zKf~v@W5(`lv);2R31B}wIah-LPrkJY=5AZbWIBn!ng4j&_4pM7z9xMzPEs;c;Yxo&JckxeYeL52({Rn8vOi|x#vZ~c-FA5)ED z(0T4QnH8=QgO3*NYm0XC2D&HlZy*Ugm6C;|hvKRSo{`xB zOlJnq&t-Yo6+u_glnLG`eJ;AiqjsrR^)*;nCfTgxbr4|afBO};iZmJciU>RRqw^1o zD!iQ;N1x3PU%XxWTOVR?_L*17mgymu@Fi!*+DYhpRorOe+A#MG9DT}1ggT&@z+F7o z>hu8=_Rc(&tS9Zzmw2AIL2mKX{rX%zOMOV?Nh|B?;6{LMFd3E{G9oD)3{;$25O@cmdp_>KXXyF3R`!uF6fdjlb!1Pg09^oSrh!p|Ory7r)1L7eC zt@J|lI+!1Q+Pwb7y$~#A=42n}o8VS?`W8@!xy&;=yqRvtfdx*idlzoqwuHy?Z~_Cg zUwf|jW#s zx>LH+7@gA(fjKahO1r=Sbq&KhPS*?AGI~IvEDi1FPqR>%AYN@?cJvO=l9O8|+736; z#0%(sAjy5WbB+$}mvP5#Q>R_i2ty1sg0?_ce+Fg;O7#Q-R3_O6F+b?c816v8P4R`m zHE%+70}YFHn0wRF?Atcr(ZQX1@+bh$0C<_vI6Ibq?%B+oVzCLQV|4V5WoNWodZpEP ztVi+IfJ-?8v2V&|Ra4B~LAj(rMPvsU_~bY3;}a>d+gx)(CKn)fFa1OYPlut#i*5-S~IyY5LFFU0Akz#X7);&_9K-@DvP;U zRfeh&`Z1vxcjaGb+aSSOJ3YD+c;&~u0%#Ngo(zggnE2ueNS=1euVU2*$pdi7&u)(K z(!Q$=9pK%1=H7amQQvG5TQ)={s7i(g9wrVn#@GReBEY9Xi~(;7@B~9lwW@>v(Efx3 zRCl&+0j~tO3uDx}5AU{9lkLgnZ5_ZCwGUoH=@=^D%G^HBtdfY24Iqe}LC4^wA9TzX zHQVS0zTk_SWT;Yz4c1XC++m5R32Pb5@A@X~x0cnVG8ISA24Kk4Msg6?Yqg4J0QD| zh0pJRR4s(HOVxI(e8gwEgWYA9$7RVKY=8M01W?5MQ>mN7`wAFPuD|Nrk(`$ZCAT{l zoQcj<9JCGuXJHP2iUT8kavLDJ1 zR}|(qZg+=6QMWJW#()i9dLIbg2;@|7q+3;q@d(Mr`Marn1C`s=VcF~s zoe>7O%t~ZXo_Vy4g;(dX$;N@w^RInCj_<5f{cGfc;`i?q1w5#|>CGG1TPoBI4;Yw6 zAA1(NfT@|rB~x@0lrMe_Hg?jI>>c&l?P6GiFfRwAmjR}+_6L4cE-qKWpzRP+1rZv3 zUf{CSt)hid;^oISAU=7Oai0P)U|A-Q1i6gNO)&Zb(+g<}{G727qz<@SKs(S4x-xCa z4KQW2kCi}%EqHA&pr_sK}-E70ijub#cVK#Z(!plcc|lKC+%25_!BoOH0y{q572_N2`?<$)T$1SpPi z0k@I?IIp~NE7%fBgBMFtz1)M@u%GeUQMk&4pn6ArIzt=TvAUJBp6YV}q#^goWyMQ3}Hvb<1!bea0SV z^gLohFM#UYKD-@bgoRVpHpO=UMIib^aOP1+57s*{odxD%H@?^o=?|&}#h<>loUWO% zJ$(lRE$kj03|Fccz*~aM!L{F0bMIeCf}V8Y*o&pgM0?NzN7TvY?^DG8|Gej6D zLxz0)UMt&9jTrVIdR1T-%Ebm=IuEuC>IT&mfrWrNst%W@*bsokIOeC0ZC%rqCei-= zk(;?=fDevQi^L^}%dde2fB;XmA{$>6YtZe~_hcrW@!e%PsNF&f2Qg<7cyNKLTW3Ez zj2o+Sn1vra1h(QsRlq2^gT_ETAnk9eXfMD3a2@*SMF{4c_KS;RRZAx|Vn|mgYnzhS zxxiJQr!#hZz>-u4VP+LwevS79%6E=!Lu{dh9n@BP6hjFJ8J&%ZJm`eVKFg!om8fTn zdoxP~;G=|9);rqE`}=-;R}O^f3ACr$g4$<*)qD4wCbMy=_GL4qU_=Cy7vMb5_`xmU zTObe6WTQ7YP_b9YoN0_vrJgZ~2`4xL}oCW>c6Tb!r;%c%SAuc^GL-49U{PF<^?VWHduV>$m3ZZu4 zW$iCRLF)$TsGx^{jWKRq$F+oEai|R0g=&-w;;bO)f=E#PY$iBwA((-v0M)sxq7ieh zh`;~nW#?I_qde=zWDEFUOfVeo}w=VhQ5NyJ?@x00@gtr+zu6QmKnf!3-Z-v%pa~bZJ4ad zT)f0UR`$Ppi(CX=w5F@NGRX4_nEY36^Htz1>B&(jyus23$6I5v>L*| zV*`C47e$dKM#WT+|oz=cd){S#alexDaZO-IcKvov>BS|Hb$&+-&smJ9S z?rIa%RMRrkQ4XbtiF^`K39~70-FDJKUjYp~?%>BS=~G*y`K`ade`sbqGk#Dv&YKQ1 zG#CeS_8gyf{}2;mz4xsL+$Xm&Z1)BO zeAg0}>mV;a&`w_f4A$SCekBlMkTtZV@`iWe`Dx>V>Dn)wH_$gg+FYh6;Qe(yU36v- zyIdNG5|{(^vG5k=9N2_1$(Y6i`CtGyJ}xS?xEj$f^K48CwG$?bATtY+8=L#|wcQUN za0t_9oXgueWev8wO0TLtq$O+rePc2TCicS~cQEb&;JT|#U@R{IcU$o31Jj#qw7%Oc zKnIZd%CzZu9|QxCDq{4_r`eI;h^LjcRP)Tc+1D%a}J&iG>HMuJYTy;ox`F+p_ z-%&OuMbzhaf&&e4yLnatYG-2d`>*dmYOx7DF{|0GyVxjJ@G4LQC;`;Kjvv)|{=Q~9 zuh>%irO7x;hJZO2C5(6>_KGT|?RH&U7n zq$|kbn!?=x232@d%0(_>PJ-wL`PY^51%_?yvkZJTwy?iM6oC!6jTF%{eIP+_Wgl}5 zU|d3Kz;Zg$!TIJ;;OGr`{#CHD&Zi2Etk!KQZV03 zM<1*6m}<&+=|0$Z%oFMDvIz_^wJcs9Ne=mn<*>8;u`5Alk|bJ$lG< zFuXwEJ3mW?U^dq95Ud+Ue0MIO(Rs!h;L(9UzVOON4?*UGn9g+DSYS>gqX~p7FR+_!r)@GRS7nAt zbb-}ks%Z>(m&42e)uHV$VlC*<9%eCiSD&)Gat9kw2xp7xz>fUE#_Y6TOywOuzsVUq z$Osm?1!f5nER90eT)v|SB9IQ_8ZjR}Hq5P?ffx?p_>VXI24cY27y{8K#!;StMbV;t zqyfrS$-BRV81lE$wgDAbG^^fZ4)Sc=&3Rs;V{M)x3ic6$K^4RKN8Q;Q%Rpf-~uu19i6AU9DBw)^6n~$6F<0mK$~5SNRx~iIG;zkhX1Q5!oen`JK=O z$q+%|OLXH}u5PWL64h;@C6z4)U_^&NbR#_@h+6OzOGJvHLYaD%;fmI{(%*|9H3WPecyT*VlyEj2%@qIOhsIIvVw)~tCERR zW7@xK;MJoh7h?p3?4JH^G}9}3i1`sR$+DgWz4c?TNzgv%(oeyF;$<+->fo{LgZW_90SmuIHzYV$Aaq9UYrq?J-0B8vWvjef`Z(OV^DVAG3WKtCvbwp06!elE5k<|I~~j>$1L)<)1f52U8fjJbE@LpSY}gC#J4 zMWf^Ik33(Y55}QIccoPe;1g$d!sTI%6V5^@vamfQZT^chQ7bsD?BeU((voSatUovY;ANlW`y6{eZ~y1^bGH z{;=tAZY_;_6=Y0j8F)GuCeHVE8q(gr(^gZrPau+TjTs zbbB2$4G02xUi+!ZcG`AXBfS#RySy3O^p%ZpnwGIGN@#@r&9 z$Uv3r#h-uk!*-Zp1p@dVho$IWq5tIDuhPQwuGMF!eTN9ID^c%6WEF7pFrL=3-22q+ z>`~>m?v7@5t`=Rpkt}#1Q3SJCN7d@AvGvl8n__V2YGZQ7g8Dyu=E5^#9bgZj|GHH* zL(Rzmi*zwN9zJ?kt+o#f-#`KDAHBK@VdKKwXcQaU#tJC&^y7ZXO;lKvg1U_MA&aAU z4B8mvEjN8eltN}8P|v#x^0-OM64i`!bBw9DCQ8`8l zYJbj<@dtP#p0)X$)LQ^iB! zyhk{wJxu01f>T7{8I)SjYQ~?ofA0>NvS;GX7OR|#pY3i~mx+Ohz&So@y6LJo5MS6I z0w&03nE}jMQ(whkvzWmEyoxJ=b3`>gZ7|N!9uF*{Lo3er$~D!qkh~GFdHGp}7GMH+ zbLL3KI?sj{tGz{sQm5jW#2o_+6x|9$$5e_^th!#4ucR*+h?PUgUyk^+;}Qgi~{ z80#_*9z3o6qc0kF)E0Td?oXdJc0iikNiWhx49-?wNArdIp|G^LW%kMX`Njy(MLs!b zDO8yUbuS4FI6UCVasubsUg$TV%hd41;199KD4c{AFgj63?|fz;2D}=`bL-aX5^6GU z_Qh+y;nfVAfMKx$WpLdYv2}+uL#Y@5n-q)Ac|xFPuI+<6AwRi=PpeTMv2KsX`ltJF z*Ssuh?+`q?#+w1zi{54s%BKAXy&!=Lw}7$S=-$!xLe)1h0J0(?MJW@(^9XVw7C`EB z(434a?c@S*`j}Cqzk!N?iYB{?4DR$VH$JUw5UO8@p?DpVKHv+1Y83?AMfw8BXJ6yW zQ>N<2&LMxxzD{r$Z!+&9%2e-MYUz?oCUqQ^kcw*Y;y%e&S(TzCv( zZV`<6&ju2uitn8lF#xW9cObP7()RRge&#Kz?K40fGA}$k+8K&Fh;9O=t6bg3xh{i} zT0X^a)Q`B84*E0K{`BOt+Rw0{o`m*i0x!I5JLSg^Ej4Fm+kf&>b}~=9s46(CV;rNm zo&>XOq;u*(K!21-mAy$UWp9UR`{Nd|dy3$xSt7Q~T^7%BQ=&C<0jLq7{rT`HI}Fs) zRDsFxQSe|;PB~Lr;H3S6t&0rCiwCcL>>7r?6tF6G2RE4(9_7V77CSI~wJbGJ9Q0@NwbQ<=5Y7l9-Rv*@gc*A7c`(a# zeF6%PX*_9w&I=fL2w>MsO zs)K9?1=$ZwGE<6ph}h{=;OrG4WI zDidyzh0d(xzOCNA4gCG@v4c-!jf1Cwbolc~083m4?^7?Mb(IVHoJwppt-k2XEs}Yw z4ZiZ~Ba89cXGPRS`fEk$?$fSfSfb(==>Y-L#|BgZ+6M6iI`|Yg2pX2L(?QW3w3IS1 zN9~6$P;z9hHLQaRr~p8Viq+oir(I=R`G}#l9i#JsgM_Q>r|hssPywh}`{zjZl~7f} zl(a$TB{iV^U9e0LaKOVeGG=>VvmoY`j`FbFsFLC+j9qmbTbLuLm(gwII#r-DHhpeM zD^hPLOcJ0h!+W7Jm}R%9YDMgRycs}|#+whwxRGlM3e@f~il^^bT-u)ta=rGIMmTSD zkY(3-1POQ^sk?@r|9-@LA|GFlDl3Yh+k-;XnEMr!{M*A%L-TFaEl})0+)d`+PN;U@9OyUW~gplWgCZS1 zetOx^a=6Z}>JQ3V1`7lYm+ycJxa6rfy1{urz!t<*j{|9c^Z#03IA;GiViC`SfO^m# zU;p8&+CRF~{tFC-D!EwHokwc_hr1V^#CU+0pF~KMx}YVY&cjn?+##$JdRrmFLEMab z7DEG^vakP1W(l`?5*Zk*>xS6+LR~**g#%yThAA-WY%00rY8IG}sOF!%0EMd*i2*zW zq^79?mwr{tV@1?$f_o_=ROMo50>7MfI`JetFenDKn5vq=IX<}dv+o$@dt4236lia5 zYT%m?F2jb!d(j2#@4>;JiS!L5M_g=m|5C?Y}$89hw7r-3>7ec`xm0t3=tdc!bA>?!Ykw~sdn0U`mr$u85pZghD`~0X_gopXr{r$$LxfiC|Hn#%g@sTDd zf*@VjJ^uJAm*s&{wg1!&1=!vw+dURl`>k=PYfO6`f%UONZnJ4JR)t`Wkpsw-T6_l> z%Z)G|VIaT`G!_K54JruEr;7uE!KOigy6s_I;uIHT7pdiFB6Mw|o zn{O$2S8q@ims*^x@yunq_JWF-66{kMbiw*ZkAu&Jd006$2Pe=9`X=_6hCq-A?rl1L zcQ_idxX!xk(%JF$_w`b%$UqgF8KD9k1LFlXB&I7^(EKV-*!G zg9*mozXOWH8q-FQ?BB(5QL!^J>I|0>>2xu>k+pw^JH*DvKL!V`t4ALjI%qI9Z);m- z!Gkiv9Q*aL@|!+pirJ`*@rJy~*KmX}AFV;4zyItO@POIUQa_a+7y?eQ>AaEZEZf^9 zA+7nb!!q~&iz2}nMQh@<0A1=jxTCTqNm)}nWft5UboystvCZ@EJkE}50Cm&P7k?f! z4xyqlpd8@FvIHjCY*hzQ<>Iv+YDwP=;F7%7&tz&>3Hg! zZakY!%Mds~p?ylxM*BhwBPK8-xb6wo0ixT2mAjerC!w0!O9tnRezuAMkwNRsYILo+s16)hZ?|yC*C^CoK8RpTn|f2WGthb`m@@U=C{9 z01F10(S?_Om-@FSZ|2hdQ(%I$nCgH=s1=^vA(c!!&Q5~ZDFMcfTLCN^cm|KopFFm|bS2n^$v7?I6L2KY+~3Qjc`#`ONhsd$8TVKlWP)Y9fTsLU^fqG3WD1 zW!P8Wd)_d%kghr$>^q?K@X9`WgHii#pwBo%B51VWjzl`%_K@vyrXE7OV=Fg%p|M%K-|^z*@6NM&TrOLu8cS1IZm0gLn`d-VIYf-`SG@;2Ig#n52; zaOep}FgJEBV7;F=Ngkm`%ceIzep1ZQKBL+n7n70jY&%G&O!Gy)0^l$R#MTrV8*J`K zpQMAd56eI@?RXKOcFb1}8X}CAl(eZP3~d$!_<_6`6}vyb%HZ)8Y|%9XbZmcMGC06w zx-Kz4e@-UO{mRfBvejRqvaPg%3pRp2{uNk5DHzMjnook0SWd!-Ss)niUV#!@#dZWR zaRw(u2Oj~2%82z2v@`z8pz;RKJtL%-J(ztE*s8Awugw6}fa!quPUK+7uQ zL?oyh#I&U&4%yzyoVu#=_H44IpqFza!JqwfgAV|x8$0<}W>f(7 zdj?%c4Kz#D7od)^IQKxQAOSZpFX|Y?mWO>(DMJa^RkDl*m{CU1Do9YyW$2~8qVOi& zn#G-(Iw=ONiA)k7u1ospak@MrHAMSI6D8bpSuDK-tc`+AaBE+_;3+2Ig(B#2pmgn! z+u;?=6RHe1FwCQ}E~*w()`(rW3q);k$A|YPt$p|%=&p2gA~)5z5d+Q!1-OIufNie}2Pe>gp3=7^y^uMt`|5H3h6ZUT_j|JBQUONlLHYjv3Zp zpjsa)*sXxta(W|629fz9oguVbY=L6AZMr*KRE4{?D75VnI$xj;T6!FX@j`xy zIfMm+%$p1HoZ6r;ZGo`(uGn)w5S=wQIHhuvOZI>D#>4Gf-7FoT4%8bK-ytLLdiK72 zUa0OWGkI%4P*^j-_5YT)zE!N?o5KyFD{;6jLq;!kEtAs^x=zaKv(aTnR->AT!@?Cg*;SPu_+C`dg;$@_8ImnV9$P1 z6z~~!&!+O>$SNL@>81S@7VWnN7`?D!Zn55aC5}Y~)E;fAOCA{63hC~Voc<6e}as>AY!={3)VRB^&Z;;8`H@9Fg2sNVQ@bv4}%cKFf%437lPZT z4~-zeKwaS7W9AjJJ(ahtTZ&IV1YP^P(U1(x$n=*tr&)6iSCF8|0Wul14pO}u8q-RU zTPf0T{Rd8AV4J?8Y5JUXlU0^!c71-2UK-JS=4s4Y4D-)pI4=l@+RVt6Rc~GFF9&8 zySRjTOCOKVg8{2=|B(G56%_0j0nSZrZFFt(G(0PlpY8(M3Pdt;fUDLl!M%ymy zGCz3a^8MW69_Rq%dChBsjYk*)>pg68fa|sY)y-04;i>l9%vM3~Z0*xe79j1j>vK>5 z+e0v;ZNr3*TlBt{n;7eZ{phbdlB!C2izNZH zUYF1-+7EMNri(7wZ=*j4K&F(T%k09^!c^V!U4+SNbzuWcj`!~d0|M*SeV{WO+V``9 zpe(aF*4AmCu<~T0+VlAZbc5)oy3f@Tar8UjlmeD0I@9Ev_>b>D#nZ&EZgT-Q>d{MJ z!&mOjx%A-i*ZwQU@{;yh3^Rja#KK_6{m1>Ob#!Bi|9NPyP0?Jg1n;u);e|m=7WSgOv1XUv18R1qkK?OwgyFY9kWWKZV1)h%O z>{(0&pdQp%p4P2pf+|9p`5I^1A1=KA7=%yMPA@NQ80RyGRaOoHm{rF;hswZLsI5V( zjRF&FKxBf>zRDMT4cZ&M85o-BT}K8mS>Y8$0ef-Us3XV_ZVS(v*mvrLmR)q$A9AKVQl za6KCM{6|o)+-+ zKaeX37+M!8e00x~cTEF%f@*n|Muu_>I5Y(0S$Y*WMlkF_i&t8-roM*IeQbNI_I^IlB#Xx%N5}4 zExp>G7=?1`rkR~7$a2tV22V~ul!4Mg4r&_>_F4>?S{I*cI{V`|UdRg3kz+}Jr-0(- zk2C)8?1QYK5+m4poJ;&B1WwM0oRw#Z(bGC?c&$3xu{I2u>~qr8=E|t z_MC%M0UOMKesoYC#lq&9wsIAk8DvnKITi`Jgck%&I zxAKm@>7hnwE^npV>IbXBVXAzEe)@#z4b+JUgBa-i+aFk!l$V&dz}HVkixMXSJhPsM zE5Ar@yXuILCU|Q^;D9vfEPz?WVlyU9@Ks|*BX2G|jRxKQx>Ikv?+$~cTU{IKP&Fgi z(_yc_vq--BBT1 zxP>54a>^*Uz*NMcO1%dP>m6|Jp?STxxi70*8b*4bx3{h`+$!`I>tVNAE7U>|^MkRj zgQ>A*pf|gc`$cD9x6@#QOkSGSXEWf-dmuM*x$MQbdT=&DtPzQ4?orc}hOxdlaGQ+Y z0j?kw6qj6_8er-GEtBTyOfR4hSDV3-7E(_3Q`IyWkAjHBL^W&Vg*mzK`zfFQHSpa;ckZ*8h{rpMb`DKs|`bvhJs{)Oo3SUL|Ph4hFcAZJxImVJrfB9jsD+J^b;vPe2w~ zgYn=6uJItK^bnYiGSRxPJ?>9e0!)mJmAQpYBnwhb9$29aYTsxURX7839h3ypzB+#6L1>pB<^pLU&dpVFZE0!+ zPz61s35;4D8@(lQ(%`*X$FzM-{iWZQN}GWZ|w%+kzGuI&pIU=7e&o*3N%S6vH+ zraf*eD?DYBQveBSV^A%(jahXVBbHfQFTl7E@c4LoAc;#>?v^2)dqDGH5po_dKKnE2 zW))Zym8(7Ziph!3?K!*U?yYO72QBT{WkU%WZJb$KC?qhR>8`A1gO=yn!{A)Xz>vyR z?RU)=w20Y8zu?q!bbl^yg`r$C^OZ4M3<9n{o-7KuLvf6rX+akf;zkEh?n}k6q zDg~~-FP$OQydeO#=^_`^42#_9jpw8jJQu{;!q-@qAjf(W#{-ali~%~RF3ugi)?@HM z*ji)FjmNHXN#iDo79&PudFLNa=lsz}|G*s^G)2)#yvMeI8uZWQEuf`?3-JVPuJwYe z*E{r&FG%~nO-N^uU}4KYV|#jLhj+Yy40~|C#ykJ)igpK0*1o&MEB1#38e0GPsb`jx z&}at%>D?m1`#rvX8Y1-kZ^IzGK`rCiS;LS()yyCxYA?fB+uF_PE8xoAYOE)8c*sQh zqB7kXl)yxX?JPtGcc6m>8At`O0QmPL=8OK1wa^d1_HB^}a5bJDW3 zr@%_rpiG0V-pzVu<(Zhs1A%}lk-~FRXk-BcjzI;ii-=as9h%V|Ek_59s1PbVf0z@| z1p8t99}nCc-4b%;jVNZ-m5*d>8^U`p@6NrAw)Uy1~Ob0!Z0Tw_IoGvT@XHBiApFwQ}P^4@9@&6NRLJYmne(y4s~ zO;q99`$WUgzkE5Nqj`Q6o63*Tv0BPRucrBR1F$wFueSGx7cl( z1c*MykRE7ed<5|dqaZ=Uu+K^x)GcSQ#9-+(gXp#XKc5`t_6A)?lgA)yK`M=`qW9d6 zUcg7hEs2$EN_#a~8ps&CECB$EqyrbVADd_}4suo4?tcsT0iGW4GXkB#I z%Xeo$s{m~tVx8b1(`XgMvZ7->DWSNLD>nkofp!l0l=7&6IGzL0le`qyQ%#q0K44x% zwuryK_<53OI#&_ms7hWA22=^~mSg(pUx1m?&FCpj)t-Lr_w}cPc4)fgbMnAcmWSJ5 z&ewD0yyDbKJh-}cklz=tt9Vn(vu|+pPp@>tA&d!TtST+6J?Wr=^Y6N`JPPRCaF89t z%Y&uG52SJk8j!xhbYxWYW^;=+Ab~#w`)R2-5cdG2fm+MKSnQ*BpS@^;#wG}`tF|cd z1{0o?X1BJ^+~TM+&_oQrpW|Cgr` zsb9@1oShjNA6>?$nfL$61!qs!I_7g*d&z@F1z#{4Zy7p|^8ywY0p?}RRnCPb4mTg6 z!2#}EN61b@b&$G0G3o?~t9*H)!a0Por{YgPLKNo90T4?dV_Zi+d;0Q3?}aszMv@(P+LRg>O<1f`S?m!O_a3urj+*R?puiCy)zy$-RShc_J%`InoDA$F{CPx$rqyM>klr-hJV1sF$AOq^3hEU!ZfXf&(1l#DIFy0L^r$ z|MDG-AqJLznJRm`KQ-FS!TvrdbfDrB5 zXV%cP16FdPVvJqUq9dl=s5ygx8TRmsmQLB=yetJvncFg$xzky80FIz}XDy$rcAp=S z?Oax6x|a|K3Tz8KYa{ZL+=oic7kYVlz>k*@7(g(f!-J2%XhjDY^W=Q(b1}?kMg@;C z2LTR2%&#m47{G7?tV9U+@moKj%~OuHpZ3HpqvWy%Q?&9p``;l~bchCVmwBQ^fVU->PFdL>y94T!m9ZI1 z!sVxBw2*xu?kT;Jg_XXe0XP$VAYeX3PVY6(JOkZj$|DtmM{*qC1Omo|imfzOn|#oQ z4Cy>u*IavP9TUA>TDVq~&uEAMP18GcK9{Crp4((jCfs-h-0H^L;4Zbi7OD5#&^bGdR@KeDZh=~B!2spb^|ieWLvMY^As(a6<(NesP-l33qjD!P zA%}4fw1HIhT{l_XYq-)p!9CmQ5c`qHLl`^jtV}@d@sGj#lqI2tmw|CdJuO^(yNL=! zI~MLUtkIe2v=tDaBoaJT`|1d1cLUWfSzFmu(sry9HH=~R=*$~0Kt>1hQk@{6h9~IQ z=9Qh6m^}fpvClKQw@Gl0qv0w^)eDul-Tg(u-3uaI@#nzYGDy$7p|Q9hVk(r}qA=-h{&K zYM-z<^-Jm2UIg|t7aOiWy?3Sx)Y&##@ZuA4Eck+G{wpFI8L%aNU^R)=;L#x7DK>ih z7n&d$)AgWa&>%>_s7zP`qwTK0!zvjL0t`bUZYd<^@9W`|H{Jvr9J1b&qri8+JTU{^ z-`t^F27*|v{{4v;7PIZ3gjy|ZomAUQ(o8HzfqSl3h|YV9RlDds*;-U^&TMPFw8)gB zd3ZuWGgw$LH?5pg#Cs#ad1%{&C4cSDbD_}%C1^Tu>JX5!7c_tyW(U(@KZek#0x>_Q zL3DyA2r%g>$P$eQ0hUZ!?Lo|?voSHbXw1ZbRUP{UIHO1O=t#1C?=bsLZ{UF~JV54qyze4@6&iGpN{wbLa@*R?W=y zHce|W3r3gm!aO?V7GpOt%7U)G3oeLeC^l_*-aHK14O*9e;pGr*6As$z8tn_^XuE|w z(z(2L4&^u)m$(B0Mrqz^E{Y}cmi2B%p~r*AvfIZQOwh~-nr!weg0KKBXG?#C2=E|! zA{=C+yae??4>JrXcg`IuANDdo{Q?cD+#ByGgWx5xJTOk$p*E1?&bh~BB6 z3r%J)Fl@{s-Uw=#2b%^Z8-baEnnBvL zLw!o2aV;mG9Rqg`VZa01f$i6RPFn-1t6AF+%*lKZj|kO%(y)s4yWU-UssSs%iVjZB z3+edgL8!DOppw;m`^0@~be15#u$BuEgr};~#@yk&fC|u>P3R4vbB}{>wCjX9 z3z!ZTKY`hH<`5lhzA8OOpY$DpHntEfZAO4Cea3`OP#57M zM?q6n_TbSuQ_6*C2&%cj@)9h-$nq6@LTdLMZ&^UbeET=Zl6c^@#A=A!wm-I?FJg&Cr`?{mLaTt6MLn_sju&BrWL>MgGc zqoP`3(9e~&!+wQ)*IbGl-fwF>AdN!wd^ z+W4YREjl|veau&f`jPrvNMOL7rUtA)-~77YR9fJ)x=QXPs4eNEt1=dl*apQbB@=wo zm-m*Jh^T?qSO~zLx5iPsW$!aTDNdRRn3P_fYY%8gi#D?z zroqEN-`%%h3$c9=45+CZaP@(lktVpEXq+3cq}hNumHd_Sj9Ngw0Du(Tv0Snr1Cy3rq z1{shb4RBUTa}Y~5D>idy0YuZs@JcKP^iQ?fw{J271niBW&jUf*(g$t?vIOO^* zO)!HX2^0+i=n|lfRy+EkG{A!y{B@%26cWG?TCn-<9td7e&^an{ zCo@(BcePr@5C&ZT`p&Oqyh%h|lwUc$(ps$ft=EJMRa@4fgls64ZoH6FgSPDO)J^$(!ZF{04aBz^y3*FQ6y zM%(nngW0Z-Wi@#YJn;~^sJ5D#0nFm@n4pq6OXO*ow^X?GapQL%X36(<3a)*tMh~W7|x+~79s$Tmt#};2HL@B$hK^L(8 ztD-Vk$$N!Bd+sQg3~0eQNT*kg9snO=#Pt@p9ebuPnv+IvB<7Ew`UqMP4`Q6BfB*v# z!kH03w$Dt&{%)F7#kq7Fe(wuE!x*sSH+{T8fuPZae*D2YdUc_H4u8Uq9-Qi5T%5y4 z>hWuRyMNP;q|Jef>X>kd>evdJkX3_`D~RAiB1KodhPVAy9Tzjeo5|Y0aPZr%JlBth zM+`4v4Kt97`>t>F4<@q3M6(N{u`*fg;M92R?T5>v=$I^Az7gMaivRve`2+aMK>y%U z;q3G@{)AsOJ~NE>v{&#){e6GTZ|a_P$al&%vXm*oX>nkuQ2D(fg0~qv2Hsc_6P7U{ z=w}j6_kmdzg0Z69{B>*+1mG(o0m2(pCrxn19gw~WwwLv}hj_Ya9bXLO8D?gzSQkMX zRJ8}{ru|yGce?kwH#1B{Xjl6n8Y7&=>guC6-*<2EggWYLyE)A)2}Py0{T_h0^af0yW6j*t@|zLeqA zGfF~C{rSOPK{S9id1abM)mC??+ap{nU`eA=iU3y&Q|0{XQ|QW$I{uK1yIuZi|D;MI z^xS;Y4ZLSb2Ca7AKk!03y267O0(zssV!Od;7=ZQ!mb}4E9tMldY?ChV1<|;yWw(}k z%feP@=F4DXph7x!_S%c!`@uMf=TM5;4%CGDFa8MOV516GB^rQr2$;XB$o-q<^=Kv} z*7E{ZG(H`tG7*~D&Vu)aN1zB2?Y73_lM}7babm+-!$UL%jn6F<&4XS1*sxKV!|Pz5_OOH1Sbv5IkO3-LKLE}e$6^ok zg0?`6|HUo(fbHJxzM&0(& zy8JxYARRlVuKF*(qFs2j(>G6mCuI-vWm+^#C2-q2zL)Nl?lycb2%3d~LFWHnP4+$) z^bhMwOJ}QmM5u-Z0Eh!Qn3sX`b;^8AT#wCJwFXnUWW#75dafbaOQ!L0Y)3( z#pG)71{+EP;{q6%H(nS42UvLlrXdjIZfa4|4TX{TmuEf%k8=YXSpnOQu0Q`)0q-R= zeY4-$M_tZ-22D^L2uVw;iM^HDDZ|kabt^P}6DSG9YTA+v7Tg8Kzy{h986R!Z5MDpJ z`->6MZrxoUm(B|+=Rsq-3ch%(rJ{t9VA_(iksXITM`*cdm#Wg|O-Y+W-NT9!GvInsGm59!m!>oF#JP^iQFz z(~dX)2yKAM!6v%>*isDS;(+H<+Oo=Xhq0iBlq%ya7VB9 zt5c8+b``t9jJ#(0l@`4A$%b+d{+_kSt zqhjds-Snrx3xbAI%MXFN!I^zn=Q>hslv^7k+tD7|0rObq@hzY0Iu{STi!K9x6sntOf6qV^}zM4$$@H_p9+g@HOoY zL}wqpV+1_p!Y^7_Pk$IXSc0S zcK%(cp`d^yi;^s^z^}O8EG%eEd)#}l9H;$KGt?}Q5r~1nLmjFty4zNuoaT0P+A7RIH+jdCHD5GBc6}5ez`kqX&7xWnP9QC4x01D~3TePR|22AhQ|9$w0`Z z=jU2Ov%>migvF}Q4UG8!RIdH~XWA1bp!06HkXtSTIR72zsj*kRRTA(L!E@W-1NMyaOa>=Y8i+Pa{q8>74rqzeG155A zEEO>O%@_(?{9YiTF~=TYr+$7i!n>2DyPt6m1bVrOa@%JH8%J1M4Dri_qu>9wINzAr z7d5rF*07e&RmWzx>yOL4Nf0V0xj-gwz<9we#z0pGx2g_vfy#n2RHf<`(_@b7rKMFL zG=U$_+fd*J>1dgOT-0=GZ%Mw<4!;!cG< z*Zvq{T3NywqVpN?Gaw6xy{dsG&;+{p(D~;X^%Y}a=YC5^#xNWJ?ZJVpVS<1C;5Qrv z)OP>$2Whs5*v~uHmF3Z?eW0iS3X84|#-H|6A(Gk0{IF-xwj8N;UJz-4_Fh_8 zXg`mOu5R8y02^lfKY#dBa4sJ(+6of|+$tf5n~cxt2S4#*Bd;t-_S4n1e5gS=3=|dj zbu1+@5h`Z60>DN@ux-wt?h^I;JX7zY>25=$@=@{R%?B}59csaYQW%vv8745MV0HNJl#L2 zpS>Qtzy8%?(Ql6S?q52o1Ib|rq9Bxcji54=0PW}IzxzZQM%f}&+2vt^Ac%6td70kT z?_>{M#Sk>sO&1SCuklP3JB&gVP0-9hI_%a?Jc7oMbfj^1vqPMYdD!G}^l4AtHzMc3 z=*9h5Ktp>anW0?LjSgD#(#NZAr8Hq`+QBsK+staM;|t2YE4i_ubjaTyd)5`=zn*%7 zEgf_abI+|*E4`Top)$k(1dO*3mkh)lfngcyC1FHC`JIU9-MCX~$z`X2cvLOJLzkt51e25Y=&)_oK@F1(u z3O{;9dqQgg6gt)rv~=t+I1l~yCu4~ay_CqjF?IoC9W(32{ z>x-Aae52pBzQ))$po3}Y0AdUQv=DINp1-~E6G#>4%l^TyN{Ih_thPw1jFX;+{k{+o|P z1Fzd*n$&fXl|L?H>egC^S0{^oTe%t59Z+o>|*T1lcXPd?A-zvsQ`7~^t zT`{+yav2=lVtr^(Tx4;sJmDX08I#&m$6}b&4t7Ay} z<6#RFRnSy`9;M&6Ko{Td1_xry&pq_@lQeD&C+?}X4+uH+P;~J)-O&be;H!_L_cPkZ zK`D%%^c66HV+CY`S8OswG`-y_{VH*K*IfJ1aY#Ca)1%D1Akb}pFqQ+3yMm?KM!}HZ3LVlLR3c+t{~JUs!`g!3jr~!V4Mm# z2$}*FgVb5jXziTzW*0SUCYnHIMnIluI``DIwIlDX#5AMnGkM}28t%K7+ZqPS6Zdk| zFPeMN!Gf^W5wWzPj$mCVu=7uv&$1ry(q0G}_0W+9}G0^a*9L z;kp@Bj6R^-y2{rGk~az+hT0=^)PBOQJ?l)D2&%GMs(B^g)KjztFqpw|nX?U62WmZg z9}N^%5BAmlU@CW@1vQV)IztNn{nb~Td6%Fe0GmB0Nk@H7{KCmMp{oKOJvuJ~;2BO= zKZD>d(m@P~Grs}b+xF%KR__cDz+-^g2By(%80Vr(q_bp$aaC7lrD~#ns428*kcy|C zt9Qy!=$d|r4K!bAX-`VGELLHuimD#m(+~PMUWuJeAR?0QJcyuDPP2~#{gu@mCVx6K$eJX5#PU; zyQ|c~d!-@xrflLre7|)6y+z&yTh#9ax3q~Kmv#_6BfRG%!pxh8%9P}l`SuQlc16Bj9bkr%Zt^ys{0>um-$K z)4;o>0j}JVP`L2bn+|k?RiunncjiEeX=ii-7A&=085P`J`600JxFK+WnI~9dQUMeT zpuawJH%+%3w-BU4iV^tt*WO|$h@nms=_t`PC~6&@F|Nsz7k(ilbk%HJ(Eh`qySQ&; z+2=!HG){s}zYYd8T6=m!cn^T_b_cYG03TIBmkV8Or4MSO+RswgU>hyK2?j^O*jNDp zdEKd75Ybl0-k{)03z-E#9!UF)OB@vD6@3I0r&@WZxHC}qO zPlEHzIMzy2E{pC0cr)|?B}+568S?Chp4ku<^E+0)85}q?1~$fI=M|>s!S=(u7p(+3 z5-6nQ6D+{Gq{AAbl*@N2?*?a>?FaWao;1oRJP3-~$){DDcou^-AYa{Ep$qyvk3Xtx znN?$`cSG5chW1D6v6dcI4V57Qo|hjmE1cZ@j-Cw-mgbtkjoZjc;HyEG9)K7P;u5)3 z8-vIL5Wv#(fkpqia%iM7>8$kMQ08U52UG~?Vy;5YwRn3)}!-p8P+(w-#%1yH7( zWfo><9Fk6OOM}HVzd_#eLjU&Yqb#!l+S@=-g5BG@7!8cwg{>g2+AC5S(TXl%${b`F z|MRO4c0v?^3_$E>S#AS`alHR;AAO$a0flD)Ti4$JXF3DSFo4mi0%=kuAA0z5afcDX zvjLh7=x5Uz#Bm*5J%fn3BA_W5cbyqv;r(s15GOueZjENdIe>t@i*X5D^M2U1qs2^* zmfn6IPU8x`dJ!_A8jL6FU@W63)GYp{+LFy=2O0o+Wlf5Kg9 z&(TkZLSOBGbhMYd^7uH~ujb?vsStZfi$;gDe>X%fXl40eZ2+X>Dwx0sVo7g#Y4@3C z*0Zz-FxDtLP}`*TJtSIQ5SB2d>rirzyam1q3T4HNkMvpOju@DOp#7--`d&1>q^rsj zl8)1%Zuci2p^J2ETBJbd_FXM1z*(U;KmhZb%{3N}(HStoh={Dk%TGaDbaRw;f0>t0 z-<3C#Cea-4<%)qUhUkJj&B&PJ6?B|seG()Uj^(yn{`H^?xWLk%9s!ggY#lPDZm~%W#(1U=D2)we0%*X0zVcWzLt!tnt-57|$E$&H zjwU%9)w^k>8;xe=)2+X|{aPFH2 z1I!Z#GQ-|1@M}K-3svdllg)u_215=A@Dm|CrHTs!xE6r1I8n)?ZRe#2Jk}UYMKYHI z(COZyf^&y}yWRn18>Eg%Vg>>2Ai9}Tt@?wpfY7uw09Ov=g>SLaTZ3pq-Z|Y1GTl^k z%$1`Jcz}910}bQF1G6n_mJ*9tTa=01I_a2h#&|afnAd(_9E!ttFM$slf)#b1dUXu4 zkU0wkmgki68tO)~T)q1r3iNr&A@*(-P#DM4-e7qwc)ZGOa7Fvd^N!3DF2rzg0=$+X zkPhOi-W>)S&(CoI%h$mhZ9_FC*aEn*iq@*4t2MQeZ^{16&1{bi|72qk(+g zr6JrDqL?+RQ17K>fX$lGTs4V3njtBS;rj4C@F*U_pvm^E41t&eji_1^!T18UoTnXm zGX}cpN&BVXera+Mq??a#Fr?Q(;UFE{L<@*B1CiSM6rQw0buQQrC}270yGL87acQ<7 z7y944223!s7GM?Znl;XV*$);QU=1`p)eGJ&9pGmUpMR3mErYJ#SDPgR3lMo;Of^Sd zk0nx2C4y$)#tfCM+zrv_o|QqJhcZ!|zIzmWC&Z=^;@>{yJgT-qQ)MP)`WhV@2%0(n z5ctLCmTA7;GkdWb;NgazPF`@t?iSN&Z@EvSpOLCVdt56^k2{lT1mxv3C!-!+2cgVy zdpCdMRW$&~h!Ch9Euy6|hc6<`^zq%NBMybK765sb=YAEpEqZ+H5EQHGHaDK6N-nf{ z=R=F_O#aZE^sR+-*0L^8HfUe$Co2QeeGHHw1Dg93?FWp5MwtJD>%-v2ARXS&w)K{- zOwj?(>ls{(4&V4m=6Y2-*o=qvdR>LA9OCZ9r7<3=_q_$nKtDtW=}7R>)!O54i_S&; z`SW|j7{wKRv~q(CsACVHb@?Y?#&ao?Hjr^L>>ec&oK^z7xdoz##j_6sgLY+0_|&FGb#6XmJqt{kG8T*-ol2@1 zUF-BEFmUy0cBfdTxUm!qGG|Ov66Z&>ABRLw2ZI!-pWrfGKojF8lMXadGf0ODL21|O z-MYfK>Xw$T-U)@N3ea`md?q?LXY&NrsNB6JaQrdA^tZG1=bGX{0)`mxIDk>rp}GQw zNWXcB$^)x>G|dXZ4)%ln>29zhke!EeXgrgvK#O=NYs^fSEN}3{H8AeUvOjg_#9g`S zH3Gw3dwHy`$?V)iS9>z31;}+oVfv5yq zQ36ykYpa+lT~5N++|fN+kQ+#QTYxg;uxfAmngwi_X{mald1Zt7fK-$~+Yjyc6qWB( z0sZgC-@p-E?SA-Qe@Aa-)4UrXuDeF>))iNGs7GEOM{a|2D8^e1raRhA%tAzs#?eLo9Y zI5VM7d)opE5Sz`*T949FKp!U&6dZZZ;l^Wn6N+tnJGeR$8lC730{-ol$HA>ZQ__(V z1IeJHYT=s2XK-Bf8z!@0=zJ3_Kc3-tRgV!)(mq(W8 z5HIY_0Xt_E7u9G0+S^T#R?=ivu}F7;lx^!~Q^V$YlXeCzIhAHZ(A)w?T^pd)S&wt2 z>-YyEy;ElC8T;K2%S?w!KlozU?(f~8k-+;cu)%B776J!d)5_(L-b`2tV5T!15^4fi zNmdQPT$kvxneU!x?twh>Bp6T+VhQ0I1tlWXMH|zi(av@U`}2bj=Ki18A7u9CE-=P{ zhH@HrByt=klr93&ZRoCDAl=t_4F4{K=Ho${vnGc zdPxu${mq?|-A!oNjkQ;4pBw0G>(qxu>ESw>zWm)-1$Q%{k1|vM|MSm}b0ckB{rNXj z!80}k!I|%-G(vv^*sR*M_JK$fbzwt#Cpb0g|zqc zacML%D-A_wIpQ*bg=80SMj?#@*oersy!a%IzMjRXZ%B79u+3iR$f(_mYIHYh-`wh* zg!=7EU>ASIi#UO3P@o-jnKs=IMnu;L7(Fz)0JdSX$e1n%C4qFXtO@jqxLRP1RuJ&4 zZBae0yu|86L({gsgJ8jntn0fUcT_os9<_gHrXcMHmDQ~m0pcY_M1*1;KXzya-7 ziz|kcc|jO6ShZhEV7A_T4h+cJ?gHPenq$aW zwK(j#4Fp)fq7MP%)H_MhJ)zx^_q<3Uom2r(~m>8wg>D zx-t$|K)_O+NZQb<+ig2KQQF`w_6#!}j3Pj-d+#vE##{!c;QAww%v~U#QL`qxog1V& zb;f4iJQB@e8LABz3C^0utpHqS6X;;b7r#j3)__V8;00S?hd`W1@R!Fw3b$P448S}n zYgKgc)-7Ldw;9BB?5Ko4^(h+O4lBLIkibC^SKox}23e@IvDr>(?a0PQ%XcP zg5Y}7c8Z*+157M#@sJ@HCrInD1P5;W_E?biOaS!D`#Jd1#gF=vOZE8TBHqD~|19A< zWw-uM3DZq8e(O{rS>?S1aCT>H2C5hiT&gvQJ2C(I9=A})zBsT}I{ehLU@o(~l>oCM zzzbAWbKNn>mCkD)LLR6zJ^7flwO^$8?_Yh6)()?6l>NpF88RAL9ucM^&CWqE`j87}idnUGfLn7ZfM<$GaFr%}*#k6etf?sC z;Q}smnR_z>o&3OFtxFjfeNDUz0J&T>P#z0bsxoMG3k}!l7!QbM`W0y4f%M#PAs81Q z@~0OAZTv2N#zLhE?G99Xm6o>9Gw5CJjhprc^?`uE4DHL&85dqS{WhBMp#SI9ckh!y zmV{1wu(}4Y1nHdb;vQ+8U^?>4r>;H*5tu?dxtoFkYLli*&=Yv&cq8X1WtvJJ)0YLN z@*SF>AA%{#ij=)>ZS5Wy{n{Z@CfNDXOYhVY0EWj(a3|Rbu>g$h1ytLPj zJS+LsPtU$*!L`kS1YDN`Yscoe-bV-8sLM&`@W~IMWLoWoswx>4g+mv9!|RvJfn&)c z*N(l(D7FH5fl?#7+GGIS9u&h%e)Zw*=bLO?(d+;LK1YAg&7^=--a%8-LyKY&6?8Y! zB><13i?(^aI*@?H?qrZbT!Cbp(p;FL)z4j2e zfMKjX>#U}dC5TsCk`ZM)PAxe1G~}6w8$D(Q_BP(xrq-r?nZ#;uBXUj^#E3bVD%Cqs z`(>z8#0W$Ny~7~^jTWBHv;*i`W+QM&gm5d~!_?)bp)$6$hYv!Udu)NLYRb6*#xhVM z0(_`hSI_@O)Hp78KcaoIkFmp1I@L{ko>lI~E86!prnKj3p#9A&C5$^eI%vxXOt1#Q z;PCe_0CxvffXvQ43m(eyL~A?yZ!a)fxYu??5K&DG7&?$9+foj3r+L%`%s90PBjnTr zLzPWUPz1;CVK9d2ZSO3oT2~Ad2atPApp5?4i|;~-0NFEuayWfz5g0vxaJaD}fdyBf zPLT#fhg+VFOx`o4-5`3r<$%KLzlOrt11!`mP7ytIA_r<93}}19iU615sPeMKOf*6RTGF=I+h{)-0O7uoqT)K0@nKw+@Npt)q}T!v>HwR z>Qow#shkR;_ZSHcpmC7eYi91%N9kf!*#`2UvvTNQ7BcIBz4T*AH2L~htVUfR7ZB$Z z^hc%)GYoam*`v}r`^;v5ssEr=tQ%7tm)-I-K7EPqiOD-) zp0hAyEo0zAL5+!{Wm`c^Z-4q^E>y;pX_$a47XBbsT7hj5BqKjTEihdl;+|{&_Q@R( zH2oZi9@3sxx;j(EO0&d51NfG63V@SqKSGsw{8O)lQrdWhF|!{z<5}F;LA@`_n+c#j zUy(7P{p2N+sRgumGOz6nI>dSc1df0WDKGN!$z6iP>p3Y@?W1{%Hj%}aJ= z^iFvVGbJI60mtnCCtn5Q30WW&Fia}zTVH~rXGBep$7-O3uOg-W_(J+auRt*gP~n;H zbnJ5|YGcqmKuH%qy!iS7C{Cb?*$VJFBQPChyjKB?rVPFJ%6(8Rw!OfOW5EozWhhaE zaE6-e&1dv3@2{WNbq;}8Obd8v1`tpp!l0P}+%`U(>!_S!gZ3mg3 zpPQq@1PnTRHHk7jW16#n{SFxSXWO4Z`?s`#HGu?NY|#)H322!B3rms4@z+HPw=w1F zxah0@{`LSuU5R0zyP^f~LetwM2&+G$ZF}3~nH8f>SJAdm0?D z;|{91EUxy{17P;8Jt_wcc0b*tmW@H4yt-KiejCmmM#oq0f=%lqi=stpkFz$&)cc|2 zh2{1@FkWc3HISgozJC*1n6!c*)J@{jJ?s}$`5A9Pqmh^CA0LqSL7$ODN3NWteLByI z_Avylk7|dyM?x3y7RkJfRjYE-M?7^+S6Che+E2K%GFt|2dH zWEC{CkT6q-P7ts_(@%n!1Oi8h*dW?1gf$76U+L7oWXs6f4?5uoK^JI$0x!A9U#2 zYxG6ya)A*9z&gM>?dF!QvQql3AhsuZlxiX)z_KlCWrH20ZWYOxOvAx$U@c>U>h_t z?>kis$?L^AbK5F`Ses}aKzl*8mT1M$vpW9EGU=@eY8d00bd$g)3i9TQGyyN8!xvf# zFW@ji>$*oDJoEX0J}OEKL@3wAfCrc=04HDT5?%XQu@c{q5HywLDCQWp2ji5TCj;D> zc|f%Y;U&92VqtjY`4}H2ai+J7BtT4oytMxh7D4m(m^pDbWH*;wHq-zvNEu-^&6I)# zjyO7Wh1%{rX=&@5%M>6Q2+x zE8qQW*pdZ3qC@$uVJO@WZNRR~5j>>1YJ$#70adqm-5!}=J%|2%Za@3xA#|`RU3n+W z1wx?JdA+6Ge6}{xwg&~YEP)S}fW^34uUkWAaE-uUAH91Wf?hfQo^*Zj2o2WF1naA# zW-9&QomPd(-~C>1LSbwP7Q+&G9xV=V$I+lPX&&6$Rl3deH*ZTXcnZ_#?E7FUcC5Hc z?OlCH+Q|&m0@{zGe`HzVK2pp#8J^qvs458E%=1$(ChPs8FwFtR6EFuFImlZ*KyNJ_ zdq5hTld&%dfUxsg+bL7K(Y|Wcl+81==j_a9$#L2Ta#{kTR!1$Gxj5SX-`;yg28H+Z ziL}%^XHvU)9KgUn#0<2UmX2@;mG_?7-!il>J@#{S0aV4xvc7)&4hTVT)a2T!_pUrX zSZqv_Sx2RU7wW_Ij@fo-{Q2dd)DO97PeB@KlR--cNL%TiH__ay1*|8*^Bi>dDf;H_ z87M;_?RP#_p#ZGP3{vgcU68C0G+Pv_lfd9mDR;;fluM6=2v2W=8Jb01{fm3FKey7R z&C0NH+{R2V=zAiaLtH(Qdc(8~GC zCqH*!iFBw{k(pUNSn%y#`NkA2w;@*qRi2Pj$@C{Lo$-HnC{)Nw5YZj|c?pP*!YBNg|A_t2f5GUIS&;Sz)0%K6%SHWq>CX14Zk`vk z|3!p2XdikX(FdW#oOw^#5{(s>gwWnCIe_;t15g- z!klJkXH|kRut=U5eh<~A1&lumE$@O2Mh3sMDfF`1WA`H?yjH=SK=Pdn1~Km-%M z)1`xHF|}tkwz95%4&h}D2J{!DwW&0cjwD_m7!@(LCQ^8SDddUITUeL?uEiNN2MPqK z5P_z{+bAV>F{3<~riu+=AnK@4UWu4;M4wHovN0X4Vi%eRsDlLt(EN4zGib?nJO!w! z+G3;vq1QfZx^zFi2SkD@Zpm0SYAt0n8G;9LO%2L~6l$yU?K~hCR1MNGEn159ekrpc z+B#OcZu_4ht!{@m_rXV!WO#b5!p3^K1ctlJ#W4#;{muJQ}3M)4Q2W*w= zr4_-OMM1kXf*R+S5(=vsr(ANZsufIrOYRf!?6pjt5jD1Lh2hW0uk+`jjI{4Q0{izr zzBbEA4uQ50_VE(QUpxYS=5DZ*4lv-W_eFwpoeg@+16uL{X_kL;FO)nG14sKBpOGOn zBM^-ntirIQUHhgEOS&LZIT5YS5w2Ldxw}pKx+Xf9(E@W3ola#@+-B_1*NrBRNjG8bySb4c+)%^=v*`W!}S6HIQn5j1E8@mo^NYdsL?{KxOuq)bw;r zLME^KD#!4IBG91$Wpn5P#u<$aWaV3a`4dsWi~sal?8yhX%ZA-Af2x?|t}j0Uwh?*k zDF|SJUix$+!TpmwT76gsj;RP9LzqH?|EDUB>4CZJmS zgK)&9sPeen>T^=H%)(D0|ln1iY+ z_(7d69s&naTr2vt`rU7pvT3Y+n!8R$z!$1JoTZVx0m)73@Z08^fl7Bq@If-=0BA|U zVD@2IId#rgpB!@yx%mrwbkxydfEj&B$>O&HnmI>b1d*EZSd=1i@*N=nP6V{FH=NsU zGC%WhqI3%HooD#>&L{dy`{*Z-baU1yy?5#N8N4qyF{nhEtDG<|y(>VPoN2`lOwCLS0(6gH<$vCM=M_~8 zL%zKeopioa(6;@_2S?-(&SASOy6~pOiEe0fj0sYtbgNmpY`%g_qD=A~@hm zhp&8)-N(3R^6XipF~`7N`%0@^&=#VNW-Ia0s+c|0G{zY~oyP5Rqzn5%D)@#hp##cC z4$`7H{XzegJF}r!`%f82H}A+d_A*78rEax$wRyRD&+bfk?@cgXkrr$6p`|B4t*la) z-gf~X0|7R%3^Rbi2P}fL2lPpka{<;lmkvW%dar{wfcm`y!GSF=B}LFWUYG82YL#X% zZzgV{fAP{F6cs^@P`MVsnL!D3iwN$8P3*vPL~);@mVfrmYGp-1~6PZn3eVxySx&0ylLfS5$>;bpvk0#?cdUp>!y0eFZI z-lazO_o?G(jHo6s*Kx46(nJ#o2fBhASTjEH)(A}i&{ZuIH~ zEr}7PQ9sdLCb0|1HP;=fDs1l8Q9|3PthK$ z0#hzK`BQo-$03!GR2Q%W4paw)iK27YsOZ4s~&C;s1X6q z83fG`v^=1^2(7-p^U5pP<+RDSuX}=bgMdlygNY|_i|*2OQQU1xuD&^a0FBmSZbHyE zdHJmwbJ4vac%cAk3NMC8&v3ITT}^?uvVTaW7#GY4U7x25lAOKwc2LI{ik|xRJ_v@2 z_MbThYbPU=E{p;RDh`Rfti2w0r!mcVjv!js`gqC?odFc>?U+mWJ}S{=JPJ1DF*VDy zQHxHlwh2bd3IwEUpV%*tyk&dnrzN zpo?}gvzU}NSJIXY#+o@Hec-$s07lv;G3N}!dR*PlO#Dq~7tAh>PFfb&-igTvr`f%gxT)4_x89gwqJ-6-1 zy(4+j!Nj}pVDRFx7ie~6B1RvRCedX4#M>4}pMmzt_~7ga&+Ve%DAU;621 zTbLGqzw7?uR%C8zfOj26!kFJGXSbzWRm&;Xq!LgRs3wnV0<3t+RZya| z!H>KK#;Y3B5j^AX58mxIXIa6ny;vSW)7fB#31isM0}jwnOU8^kf%ez#cG1s2qb$02 zrG`I!q#s)C{qo}9h~v@#9$%^$!H8pnh+LUI;X?G7)n`d;P`yMcq9bkW+@)#o9! z`wA0>>(-W)4rRoK)}lv785oOooXsg-xiXfKz6}CsKA_EVQY8Z#rsZG_3s%?e@3gvh zho|+mw>Y_=NCeky4pONd!nS~Uy9uhT%VKcbNG~`ISAF#p@Fl&k>+~a+9-359lS%W> zl(nt6ImiM2-3#&d3>1Ld;00N`fo~rHTe6IhmMUURp4|nP-oLUBz1TkZzaK9~i0?w)oR>#R^{tT%P1e+do*ud<6KQn5L;Y=}mCI+O6q!`c(H zc?1Kv!4=G8(vi$fgFn69L+i0M#;pLUpo5@mzdHJY;bfstopdw% zeZIOk!}EZesB7x@o#?ZZ;Ti9<4{HxwKyv`pC*8d8u}=oULpGhkb6SkYgVib7ZX@Pb zc*Rwo01S`wz@DtZjjfXTupTc)4$wDQJ0A&o^Q>MVOG44zexgExC4Mw{p+Iv@DUYjU4QGdZIy zxhBrM_pI+eP~w(#V1U=M;Q7D?h?~m^0IL~d8Z$vgK<##^jOID*c^(F1@r&DN2~x5l zE0}gVj{Xj+%8+!uw`iG@8#DI=Uw*~~3bx&bMX?p(D}pX}wz>Gz;hHe%n5SR4=mK6g zLpn-4K+)mLksX#R#>@)A9Gy-xFm!czLfbp0FAdFNP?os^xGiI{SCxV9 zK0B-vJFnfRJ(`vmbyxwj03|u5fD5uZyP+`Qmr@#Qq;D3&3zW$XaH)(d9p~?a zs^S9Ly!P;PC^QD+1K10+t?TN+S(#cG#&-5E}uY?kEVrE=qXz2U;c2Xbo)RU zsT^lA&@Dckg^@$EZ`+20>u{d#X-6Ypxe98nIaqsDWE7n;6;KM!XaP7kaPobTI#12o zOZC*TfgB9%trHEk9B3-y{CnrPcwS)dx@cH%pY9CkdACZCo_Xd;BmM5Z<0MT3VSYjpOe?Mpc|vV`%sWJ2iE*U3_4nxa-CPtedrRjtV1A-UKs2lcX0yDj2on(zfeb1YuHlTv|F5(w@rvub?!zVo5<(LD4nhbR zfdEPD8erIWkU)SIkcMFx5X+2a03nIRX)3$1>o~USG;WmR)aNv568pr7Y#+5wlXE0* zYGT>)7N>UXle(_clXUwJ`un~6&10AuFmZ?9z2E)5_uhBE?|%2*_h#X}(YaRbgYr&} zkNLpueH&f1TnUws79MJ_@%O$!urUOMtQHNXl| zKE0xER6Sbre*Fz;yP)i^V!7m%8+L4B4Y}h?W9I4y~hhVon8aKTk&!MCelA zF15KnQg7R-EKOx^J*$>S`z>hd5i}hH?HiN5tC@Ma6ZQ<2lu5&yUrwRn!)K(`FwS|G z576gyC`aNE;nGM^83EFm@^y$cvRybk)^QRN)13~_|GUf;qp3Nouc=5jsnwUtkQ99? zEOJp*ZaQ}E_RR`ZKmXZRKL7cnw19w{xf?)l)X}jMVxCERkbP2kAx(UQ%MTP3stK5+ zo-~iL55x|7L6abFs1;zerKzBfwlW}hf!LY@0-V*io)amXKw{jqEP(-4IpcKgq22A|pjZ%4Kd^i6(KGEMnQuOd8bdpE z8Y~Xfe|6m=D-U)u^KXQ0vcb;4s{H7h5e0p$DEpJgP=qru+q)NoF9$(TLC$>y+vjgT zb3*$K-I6hxQ)3#^!P(PA29|e6m5#jn!003=`t}o}%FW(-K)a8PzCULGT-F;PoR!Lc zm2j$(kD_6pT0F{t+UA5f16mjJt!PLB3Fusce(llakWWZ`F@i4Jk)&2RL;1NGjr7C+ zc;WFRS2-7a1q5VC;Yd0sf^ZrMcO4t%(bPLZ?bR#!%*!9$ z4+d};N`>}pm&LUR%Fe&a-nj?et_37G9DYen2K5AKi!P2Ta+N~9Ds^zGWs86-a*=Ca zPfG#H;8Fo+T#Sv-wjI*ed-rj6UcLx+YPYn3b0)wj=%a_qhpN_AQQPtJ7k=9O*|(p) z^JB&!P*@_R@Cp^{JyN}TrOyT_D)BOh*S#RE7AcsIEp$uvt8z$Kl$sIOAJ`thw}H+& z#sEIvDUI4=5H40}KWL3ir2=bC!I3q?qG5PB(XFBkwHOeGy9^Sn*lHmp9ZpF(CJk!! zouB>ir!~`zQ=s^_KLEcV6>#%N7&u)vaz4RvT-uwY@a9g#?H|U{Lp_&O4l2L2UFFb1 zRC->%!SO0_eQS8$UOwhC>q{*w2OLyORqdE!lcT*49R38XUm~h z9q_2-MF7ysiCrC_`%Ed9Z8D*vf{zz$2N)i`AQLx4Oo8>>yPuBW0u6&|>C81;l~psC z;PTaq`ABM^d5l~J9Sk)iNQEnPsnM#HE#y#CTBB7sjB!wR4H!VTyBgaxaP$asNxU=) zk4C{=NxQni=u!8c0n?#Yds-TJF~J1@cDQ)}aO*o#4%6E>ejmiB1RNY1>A4FabAmmC zVbNo`z(X<@j)iei&VT^=V-Dvsv`-qqDQ!Q#W2$9O504lE*|m4@PWI*v&Rfl0nhymS z)#4nsF=>bT$%n0iNVQBDfYOPX6Xg|<%hs>INts)tFlreY6j3+B1eTQ$aoUu7k270 z11wK!F;X1ro%qe)PIGz6Ln6SL63)A5S%F&nSD(^bL|C@(?|A=a30KJ*%ifhkM^JlB zy97>x6a?aeat8F~Js>9MED*q^?V!6)YtIveG#WY&PRC5=XgPR6!J&iPdk|C~+EtuQ z&(D=j`=|lvH>q`5x9;qJxe6?PiFTdZLl4*q(osA@S1Q-*A{3$c^r4#!o^yK*=LS&n z^q*|z&a4T#s4VKDUe|>)k;!lT47CzBSoT5M1-SEfQVOSzkS5wY&AT}gm2qav*@VId zeFMFdje?L}QgRu?wI?(~NDkQ{tvWwhtlZ@7$I#Z%HSR)@ud*23A_a83n5}@ZKcmKq zQu_{q=TFWn6a?gO9<3tN&9xhZpgbi_dr@#rbi}ITy3oSx+`#dl1*J2+rh|$rEY!Yo zXi6=Ik!uCyH!OFIT1!xNC4ps@_f<$6=YHbu zgG*PXO3P$__@Y$6XSJKcNVRli3POhiES}-Ex2M{qa?VTv>L)GYXwceBI%Ny^ER#5=p`((AwUpC0sNssy-hK(C3uIXM{SW@C z5yE>nnyhqZ&IGW5E~kOfptT_Fe_c_k>U-BOo@ST>K}+=wN? zYb_6$YK~&V?pj({`4Mv+9fecw0UZeo2L~#6tZ_egE6Ql00|PX(5!44#X^+#n^?33M z3idM#0umyZ?tBZSI-jK`n7C%eAPXak!-yO_$#`TNpml(fzBky(F|?k3^P4EDuF#rJ zGJ%>ChXHWS(mH6{q-EvJacXL4`@_v2f^P!}XzlkOqnT({U_s5|@bU?!GC>9kYh~X6 z3Qmc(CAHoC&ZO%g1VKoplnhVytHTb71_C1WMhGf;PD4yr)A{fL*&(?nx*k&3R9o(= z-)(_ZBkh^YP_ZVka!yn*Xu9N>cciwC5aY!Bw##`8jYb|_~oQ<{2B|8w)H z8|{qNb`afJ84{ANApY^1R9OaI-Q2nx(JpR(@1#_UC_z2nQO>r14V$x zumgZALu&w8pl%V3D2xaCr2=l61DjZ@ugaEl49s4d!vxBe#vv)dgF!_g<{_m6QbaSD z;O>)Bayb)YwOdH7)vzL|a+Ty}5R0YNyx0d-( z>8{$Za^A0=Koxl92G}C=qyl|@oNr;;+9KJvTk-+%-#@_`zr7LJXn zDT;19#RQlJVxr1r6qH>717d0TT`g?SmliV$T5`Cc`i!*ng;Y~NK&OcZxe`p%6*Z@n zkw3W)O)*^45fD)Mn+L%oq|)8VXayFm)cMA<2kH|0K6(IR3h3>>v4^wsR?xu0pjBCN zC)XLMEC-{L4T0ic`4;%6&;2!RuB@DyPt(5sC|Cigt%AdFgMj0p*0!C+GzYL>dkUf2 z#%KfB_4#x35aY;k?fFxyQ4!oq@cGn%AbIOo1<0K4`0QSdxzZOukG8kr_F@Xzk2qp+K!N*%<)&YX*9Q2zJd-&8?D zg988h^9REt_j1#;bCC7~?z|{vK%Pgh0xTs`I>WLV$ablL7c>-c=sGHmoML3hqW0iq zX+9Z-l1tnUO7lE;sOl0Id>*9I)vyJ!k>17N(UAp-eU4Rw%~pV2;A}?e0delLBf}`C zO2<#;prnEr5S4Kq20(_e-(Euz3j$07bPyfsB1K+6S#6w*H(fcfC`~(23?!t2AOG~5 z-FQ^N+_nef;b~4le zCOx203VMKwI8Ncs7md=Mh$2~ggCq466r8Z2Yb1;A%oq_ITnL6Rsn?Gel%LZp-ooi^ zaVy^SVN~AxrL}Qd)M-5dQ(!U`e+8o3Cc?~)g3^&Hp#=N z@v=mz8c}v+SklJ5q&_e~rm3WnegtIw+t+>|QrkF69{=%Aq#+}9Rs?V^W9eWX-3bWi z6izhKFQ@^aW%ki=FMtvcb9vuXKD+4R31F%w3LMCiV&D)bG7O@_0xeR!qm(x?inuO7 z1?PS_;)K+M``o?zEJs$qggb%lzsNu z+zO&?RCrZF1UPnjLJ^1|2ArvjPq{q(?>~8>MY(1+%*C33}?Gxz@Q*ROp&l^(q2-?gZ{{})x- z?^upO{+B-=U2T8wVMq}P>=yXoL8do4@rY676v%0jpS*w~YKXZJNahsP5s)T}(@R!S zPATtP-Gz#?0t~pMeUl2IqQBUVqBc2+fn)*Q{WchvT8BxO8Y07Jq!@SF4ixbqx&T|2 zBEUPUNJ5TF7K^Sig<0-_@L?2-PsURA8P-Uc`b}q@p+Sx4QXeDiXfk_y+ z_gs_+obZH*QTBJAgfzQb`FE)_52HBL3>N$DW8gd>Tn(I7;Rx<>aLFKJ3>fz)qQOtv zBib3KR?se6+(B*t4l>QrD?>s1onYQ5(MHFng`cRQ3Clq(GD#@ zEhr9-9s|k%*#0$^rM%;l$%QXKXlS6wab_dua+mCqconA&~~d_U$;xtR3#@CPJ%`?Pj!U8@rnN z&4q2<%|*Tka)oP5b=aA=PlyG1UNT<%zpp_*xXaw#*4)(Bf2gb3w;vwm831n1qFyop z^n|*@W%tw0-8@I(0p#lCdz9E@(}TH0^4j3wOD>BOXJx-mFt(g`z6XxfmW0!Kk*6P& zVu3Vl;n>wEJRQ|L9CPkD^x9>aoW&D4cy8ZcB4>AB<4gw8|1$7KZ9kT*&`(7+6mL;Q zU|_>X@;0Ivi8;&cJp<$JR1lSHh>F;td9)XC^2`|3Nebu$ibBlqhFN zZrDG%Nd!rU;QRbkB*WnXsA%(eaNw>hwabVB#29+Vj{yAp4J{4a@2q>yGCjRf`0@0` zi@YV+JqfGqZ*^=mZQ3&)22BkO6E^Eq;K8E{fEP~y&H{DNlIdp{OWkH_Hte|yeL67u zqey@}k9uCBt>I+APCFg;4L#8@o3sZ92N?|KkvVxsX3tBy1Ro68X)n&$X1CimGdhiI z-RZDerW=ulT$7{obCZq@d?u}3dW}c+JA*XAUw3$3y1r9itZzg6sH;-+g`ir3=NEgr zM=2UkS_1a(d(GWynZ*@~dXMRw?9h`5#7kZ*MlELJ?@G4ufO=G1;Z5xLqN+(#4%0}5Bjx!`<^1GkDw-B;)_MIQ|i_$;=&vGvPDoUNJ175B9cFl3Z zEZQqyl`NnRNOAjhy7A@NW?e_?UCV{a7&`XKHMq76bcuoy@M82B2H1xn@;{Scqkl){ zQC^@}=QjQr!gr*<{wg{GhU9dQigPIML&LW^-=rnW9H{5|r7Y%zvS6OPi_k`4q=@E`8&CQxS|LZQm$Q zEN|Am_eb=;eWT<5eDKHM;*;S1p~ch0X8mj532b zxE^kvbh+pH=10|HZI}R))F(DrkpoCeNBn&5Pg5&qbZ@9mdIJv?Dp|&xPl9O%U@p?+6E22 z&uRDQ*Of!qg8t2(-tMb5@KX=Jq~cAUh3Km{&;!K2q*n1LbHK-n`KpBhb3i`N-uZti zM*Q$>v)O4e;BzY0E9HrQ3rj0=l~m#Nq{#r&M1MdNNc(y>`ih);+ zALs%6It!WI^W*3(Y0ymO|C4Fo8St&P?|0!}uK&$Wzy4qTtk=P}PJX_J>!GcFA>=zN zUP$Dj$Yz_))0uY}g5Mg!al&B@0o>uO9Tv gYks=QWEc38&)$wOTwNIqW%$EUc$?j=9c(cCA8JKBL;wH) literal 0 HcmV?d00001 diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..94920145f34e --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew new file mode 100644 index 000000000000..2fe81a7d95e4 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew @@ -0,0 +1,183 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew.bat b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew.bat new file mode 100644 index 000000000000..9618d8d9607c --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/gradlew.bat @@ -0,0 +1,100 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/pom.xml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/pom.xml new file mode 100644 index 000000000000..4ec080f6d957 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/pom.xml @@ -0,0 +1,309 @@ + + 4.0.0 + org.openapitools + openapi3-extensions-x-auth-id-alias-jersey2-java8 + jar + openapi3-extensions-x-auth-id-alias-jersey2-java8 + 1.0.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + https://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M4 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + false + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.7 + 1.7 + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.1.1 + + + attach-javadocs + + jar + + + + + none + 1.7 + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.2.1 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + + org.glassfish.jersey.core + jersey-client + ${jersey-version} + + + org.glassfish.jersey.inject + jersey-hk2 + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-multipart + ${jersey-version} + + + org.glassfish.jersey.media + jersey-media-json-jackson + ${jersey-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${threetenbp-version} + + + + com.brsanthu + migbase64 + 2.2 + + + javax.annotation + javax.annotation-api + ${javax-annotation-version} + provided + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 1.6.1 + 2.30.1 + 2.10.4 + 2.10.4 + 0.2.1 + 2.9.10 + 1.3.2 + 4.13 + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/settings.gradle b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/settings.gradle new file mode 100644 index 000000000000..488eab4f0474 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "openapi3-extensions-x-auth-id-alias-jersey2-java8" \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/AndroidManifest.xml b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..54fbcb3da1e8 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 000000000000..f6ecb14f80ea --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,1149 @@ +package org.openapitools.client; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; +import org.glassfish.jersey.client.HttpUrlConnectorProvider; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.FormDataContentDisposition; +import org.glassfish.jersey.media.multipart.MultiPart; +import org.glassfish.jersey.media.multipart.MultiPartFeature; + +import java.io.IOException; +import java.io.InputStream; + +import java.net.URI; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import java.security.cert.X509Certificate; +import java.security.KeyManagementException; +import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; +import java.nio.file.Files; +import java.nio.file.StandardCopyOption; +import org.glassfish.jersey.logging.LoggingFeature; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Date; + +import java.net.URLEncoder; + +import java.io.File; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; +import org.openapitools.client.auth.ApiKeyAuth; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiClient { + protected Map defaultHeaderMap = new HashMap(); + protected Map defaultCookieMap = new HashMap(); + protected String basePath = "http://petstore.swagger.io:80/v2"; + protected String userAgent; + private static final Logger log = Logger.getLogger(ApiClient.class.getName()); + + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "http://{server}.swagger.io:{port}/v2", + "petstore server", + new HashMap() {{ + put("server", new ServerVariable( + "No description provided", + "petstore", + new HashSet( + Arrays.asList( + "petstore", + "qa-petstore", + "dev-petstore" + ) + ) + )); + put("port", new ServerVariable( + "No description provided", + "80", + new HashSet( + Arrays.asList( + "80", + "8080" + ) + ) + )); + }} + ), + new ServerConfiguration( + "https://localhost:8080/{version}", + "The local server", + new HashMap() {{ + put("version", new ServerVariable( + "No description provided", + "v2", + new HashSet( + Arrays.asList( + "v1", + "v2" + ) + ) + )); + }} + ) + )); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + protected Map> operationServers = new HashMap>() {{ + }}; + protected Map operationServerIndex = new HashMap(); + protected Map> operationServerVariables = new HashMap>(); + protected boolean debugging = false; + protected int connectionTimeout = 0; + private int readTimeout = 0; + + protected Client httpClient; + protected JSON json; + protected String tempFolderPath = null; + + protected Map authentications; + protected Map authenticationLookup; + + protected DateFormat dateFormat; + + /** + * Constructs a new ApiClient with default parameters. + */ + public ApiClient() { + this(null); + } + + /** + * Constructs a new ApiClient with the specified authentication parameters. + * + * @param authMap A hash map containing authentication parameters. + */ + public ApiClient(Map authMap) { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + this.dateFormat = new RFC3339DateFormat(); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/1.0.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + Authentication auth = null; + if (authMap != null) { + auth = authMap.get("api_key"); + } + if (auth instanceof ApiKeyAuth) { + authentications.put("api_key", auth); + } else { + authentications.put("api_key", new ApiKeyAuth("header", "X-Api-Key")); + } + if (authMap != null) { + auth = authMap.get("api_key_query"); + } + if (auth instanceof ApiKeyAuth) { + authentications.put("api_key_query", auth); + } else { + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key")); + } + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + + // Setup authentication lookup (key: authentication alias, value: authentication name) + authenticationLookup = new HashMap(); + authenticationLookup.put("api_key_query", "api_key"); + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + * + * @return JSON + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + /** + * Returns the base URL to the location where the OpenAPI document is being served. + * + * @return The base URL to the target host. + */ + public String getBasePath() { + return basePath; + } + + /** + * Sets the base URL to the location where the OpenAPI document is being served. + * + * @param basePath The base URL to the target host. + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + updateBasePath(); + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + updateBasePath(); + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + updateBasePath(); + return this; + } + + private void updateBasePath() { + if (serverIndex != null) { + setBasePath(servers.get(serverIndex).URL(serverVariables)); + } + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication object + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public ApiClient setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return this; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public ApiClient setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return this; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public ApiClient setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return this; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure authentications which respects aliases of API keys. + * + * @param secrets Hash map from authentication name to its secret. + */ + public ApiClient configureApiKeys(HashMap secrets) { + for (Map.Entry authEntry : authentications.entrySet()) { + Authentication auth = authEntry.getValue(); + if (auth instanceof ApiKeyAuth) { + String name = authEntry.getKey(); + // respect x-auth-id-alias property + name = authenticationLookup.containsKey(name) ? authenticationLookup.get(name) : name; + if (secrets.containsKey(name)) { + ((ApiKeyAuth) auth).setApiKey(secrets.get(name)); + } + } + } + return this; + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public ApiClient setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return this; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set bearer token for the first Bearer authentication. + * + * @param bearerToken Bearer token + */ + public ApiClient setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return this; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent Http user agent + * @return API client + */ + public ApiClient setUserAgent(String userAgent) { + userAgent = userAgent; + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Get the User-Agent header's value. + * @return User-Agent string + */ + public String getUserAgent(){ + return userAgent; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return API client + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return API client + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return True if debugging is switched on + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return API client + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @return Temp folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set temp folder path + * @param tempFolderPath Temp folder path + * @return API client + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Connect timeout (in milliseconds). + * @return Connection timeout + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * @param connectionTimeout Connection timeout in milliseconds + * @return API client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + + /** + * read timeout (in milliseconds). + * @return Read timeout + */ + public int getReadTimeout() { + return readTimeout; + } + + /** + * Set the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + * @param readTimeout Read timeout in milliseconds + * @return API client + */ + public ApiClient setReadTimeout(int readTimeout) { + this.readTimeout = readTimeout; + httpClient.property(ClientProperties.READ_TIMEOUT, readTimeout); + return this; + } + + /** + * Get the date format used to parse/format date parameters. + * @return Date format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); + return this; + } + + /** + * Parse the given string into Date object. + * @param str String + * @return Date + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * @param date Date + * @return Date in string format + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param Object + * @return Object in string format + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(','); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + * Format to {@code Pair} objects. + * @param collectionFormat Collection format + * @param name Name + * @param value Value + * @return List of pairs + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format (default: csv) + String format = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); + + // create the params based on the collection format + if ("multi".equals(format)) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if ("csv".equals(format)) { + delimiter = ","; + } else if ("ssv".equals(format)) { + delimiter = " "; + } else if ("tsv".equals(format)) { + delimiter = "\t"; + } else if ("pipes".equals(format)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON + * @param mime MIME + * @return True if the MIME type is JSON + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * @param str String + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + Entity entity; + if (contentType.startsWith("multipart/form-data")) { + MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()) + .fileName(file.getName()).size(file.length()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, MediaType.APPLICATION_OCTET_STREAM_TYPE)); + } else { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(param.getKey()).build(); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(param.getValue()))); + } + } + entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } else { + // We let jersey handle the serialization + if (isBodyNullable) { // payload is nullable + if (obj instanceof String) { + entity = Entity.entity(obj == null ? "null" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType); + } else { + entity = Entity.entity(obj == null ? "null" : obj, contentType); + } + } else { + if (obj instanceof String) { + entity = Entity.entity(obj == null ? "" : "\"" + ((String)obj).replaceAll("\"", Matcher.quoteReplacement("\\\"")) + "\"", contentType); + } else { + entity = Entity.entity(obj == null ? "" : obj, contentType); + } + } + } + return entity; + } + + /** + * Serialize the given Java object into string according the given + * Content-Type (only JSON, HTTP form is supported for now). + * @param obj Object + * @param formParams Form parameters + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return String + * @throws ApiException API exception + */ + public String serializeToString(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + try { + if (contentType.startsWith("multipart/form-data")) { + throw new ApiException("multipart/form-data not yet supported for serializeToString (http signature authentication)"); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + String formString = ""; + for (Entry param : formParams.entrySet()) { + formString = param.getKey() + "=" + URLEncoder.encode(parameterToString(param.getValue()), "UTF-8") + "&"; + } + + if (formString.length() == 0) { // empty string + return formString; + } else { + return formString.substring(0, formString.length() - 1); + } + } else { + if (isBodyNullable) { + return obj == null ? "null" : json.getMapper().writeValueAsString(obj); + } else { + return obj == null ? "" : json.getMapper().writeValueAsString(obj); + } + } + } catch (Exception ex) { + throw new ApiException("Failed to perform serializeToString: " + ex.toString()); + } + } + + /** + * Deserialize response body to Java object according to the Content-Type. + * @param Type + * @param response Response + * @param returnType Return type + * @return Deserialize object + * @throws ApiException API exception + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, GenericType returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + return (T) response.readEntity(byte[].class); + } else if (returnType.getRawType() == File.class) { + // Handle file downloading. + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + + // read the entity stream multiple times + response.bufferEntity(); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @param response Response + * @return File + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + Files.copy(response.readEntity(InputStream.class), file.toPath(), StandardCopyOption.REPLACE_EXISTING); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf('.'); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { + + // Not using `.target(targetURL).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + String targetURL; + if (serverIndex != null && operationServers.containsKey(operation)) { + Integer index = operationServerIndex.containsKey(operation) ? operationServerIndex.get(operation) : serverIndex; + Map variables = operationServerVariables.containsKey(operation) ? + operationServerVariables.get(operation) : serverVariables; + List serverConfigurations = operationServers.get(operation); + if (index < 0 || index >= serverConfigurations.size()) { + throw new ArrayIndexOutOfBoundsException( + String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", + index, serverConfigurations.size())); + } + targetURL = serverConfigurations.get(index).URL(variables) + path; + } else { + targetURL = this.basePath + path; + } + WebTarget target = httpClient.target(targetURL); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), escapeString(queryParam.getValue())); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (Entry entry : cookieParams.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + for (Entry entry : defaultCookieMap.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(entry.getKey(), value); + } + } + + Entity entity = serialize(body, formParams, contentType, isBodyNullable); + + // put all headers in one place + Map allHeaderParams = new HashMap<>(defaultHeaderMap); + allHeaderParams.putAll(headerParams); + + // update different parameters (e.g. headers) for authentication + updateParamsForAuth( + authNames, + queryParams, + allHeaderParams, + cookieParams, + serializeToString(body, formParams, contentType, isBodyNullable), + method, + target.getUri()); + + for (Entry entry : allHeaderParams.entrySet()) { + String value = entry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.header(entry.getKey(), value); + } + } + + Response response = null; + + try { + response = sendRequest(method, invocationBuilder, entity); + + int statusCode = response.getStatusInfo().getStatusCode(); + Map> responseHeaders = buildResponseHeaders(response); + + if (response.getStatusInfo() == Status.NO_CONTENT) { + return new ApiResponse(statusCode, responseHeaders); + } else if (response.getStatusInfo().getFamily() == Status.Family.SUCCESSFUL) { + if (returnType == null) { + return new ApiResponse(statusCode, responseHeaders); + } else { + return new ApiResponse(statusCode, responseHeaders, deserialize(response, returnType)); + } + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), message, buildResponseHeaders(response), respBody); + } + } finally { + try { + response.close(); + } catch (Exception e) { + // it's not critical, since the response object is local in method invokeAPI; that's fine, + // just continue + } + } + } + + private Response sendRequest(String method, Invocation.Builder invocationBuilder, Entity entity) { + Response response; + if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.method("DELETE", entity); + } else if ("PATCH".equals(method)) { + response = invocationBuilder.method("PATCH", entity); + } else { + response = invocationBuilder.method(method); + } + return response; + } + + /** + * @deprecated Add qualified name of the operation as a first parameter. + */ + @Deprecated + public ApiResponse invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(null, path, method, queryParams, body, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Build the Client used to make HTTP requests. + * @param debugging Debug setting + * @return Client + */ + protected Client buildHttpClient(boolean debugging) { + final ClientConfig clientConfig = new ClientConfig(); + clientConfig.register(MultiPartFeature.class); + clientConfig.register(json); + clientConfig.register(JacksonFeature.class); + clientConfig.property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true); + // turn off compliance validation to be able to send payloads with DELETE calls + clientConfig.property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true); + if (debugging) { + clientConfig.register(new LoggingFeature(java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), java.util.logging.Level.INFO, LoggingFeature.Verbosity.PAYLOAD_ANY, 1024*50 /* Log payloads up to 50K */)); + clientConfig.property(LoggingFeature.LOGGING_FEATURE_VERBOSITY, LoggingFeature.Verbosity.PAYLOAD_ANY); + // Set logger to ALL + java.util.logging.Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME).setLevel(java.util.logging.Level.ALL); + } else { + // suppress warnings for payloads with DELETE calls: + java.util.logging.Logger.getLogger("org.glassfish.jersey.client").setLevel(java.util.logging.Level.SEVERE); + } + performAdditionalClientConfiguration(clientConfig); + ClientBuilder clientBuilder = ClientBuilder.newBuilder(); + customizeClientBuilder(clientBuilder); + clientBuilder = clientBuilder.withConfig(clientConfig); + return clientBuilder.build(); + } + + /** + * Perform additional configuration of the API client. + * This method can be overriden to customize the API client. + */ + protected void performAdditionalClientConfiguration(ClientConfig clientConfig) { + // No-op extension point + } + + /** + * Customize the client builder. + * + * This method can be overriden to customize the API client. For example, this can be used to: + * 1. Set the hostname verifier to be used by the client to verify the endpoint's hostname + * against its identification information. + * 2. Set the client-side key store. + * 3. Set the SSL context that will be used when creating secured transport connections to + * server endpoints from web targets created by the client instance that is using this SSL context. + * 4. Set the client-side trust store. + * + * To completely disable certificate validation (at your own risk), you can + * override this method and invoke disableCertificateValidation(clientBuilder). + */ + protected void customizeClientBuilder(ClientBuilder clientBuilder) { + // No-op extension point + } + + /** + * Disable X.509 certificate validation in TLS connections. + * + * Please note that trusting all certificates is extremely risky. + * This may be useful in a development environment with self-signed certificates. + */ + protected void disableCertificateValidation(ClientBuilder clientBuilder) throws KeyManagementException, NoSuchAlgorithmException { + TrustManager[] trustAllCerts = new X509TrustManager[] { + new X509TrustManager() { + @Override + public X509Certificate[] getAcceptedIssuers() { + return null; + } + @Override + public void checkClientTrusted(X509Certificate[] certs, String authType) { + } + @Override + public void checkServerTrusted(X509Certificate[] certs, String authType) { + } + } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustAllCerts, new SecureRandom()); + clientBuilder.sslContext(sslContext); + } + + protected Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + * @param method HTTP method (e.g. POST) + * @param uri HTTP URI + */ + protected void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, + Map cookieParams, String payload, String method, URI uri) throws ApiException { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + continue; + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiException.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 000000000000..efc394e679d5 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,94 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; +import java.util.List; + +/** + * API Exception + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiResponse.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiResponse.java new file mode 100644 index 000000000000..7a74030c85ed --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiResponse.java @@ -0,0 +1,74 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + * + * @param The type of data that is deserialized from response body + */ +public class ApiResponse { + private final int statusCode; + private final Map> headers; + private final T data; + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + /** + * Get the status code + * + * @return status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Get the headers + * + * @return map of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + * Get the data + * + * @return data + */ + public T getData() { + return data; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Configuration.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Configuration.java new file mode 100644 index 000000000000..40ca8cd299bb --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Configuration.java @@ -0,0 +1,39 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/CustomInstantDeserializer.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/CustomInstantDeserializer.java new file mode 100644 index 000000000000..83d4514b071b --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/CustomInstantDeserializer.java @@ -0,0 +1,232 @@ +package org.openapitools.client; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.core.JsonTokenId; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonDeserializer; +import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils; +import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase; +import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction; +import com.fasterxml.jackson.datatype.threetenbp.function.Function; +import org.threeten.bp.DateTimeException; +import org.threeten.bp.DateTimeUtils; +import org.threeten.bp.Instant; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZonedDateTime; +import org.threeten.bp.format.DateTimeFormatter; +import org.threeten.bp.temporal.Temporal; +import org.threeten.bp.temporal.TemporalAccessor; + +import java.io.IOException; +import java.math.BigDecimal; + +/** + * Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s. + * Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format. + * + * @author Nick Williams + */ +public class CustomInstantDeserializer + extends ThreeTenDateTimeDeserializerBase { + private static final long serialVersionUID = 1L; + + public static final CustomInstantDeserializer INSTANT = new CustomInstantDeserializer( + Instant.class, DateTimeFormatter.ISO_INSTANT, + new Function() { + @Override + public Instant apply(TemporalAccessor temporalAccessor) { + return Instant.from(temporalAccessor); + } + }, + new Function() { + @Override + public Instant apply(FromIntegerArguments a) { + return Instant.ofEpochMilli(a.value); + } + }, + new Function() { + @Override + public Instant apply(FromDecimalArguments a) { + return Instant.ofEpochSecond(a.integer, a.fraction); + } + }, + null + ); + + public static final CustomInstantDeserializer OFFSET_DATE_TIME = new CustomInstantDeserializer( + OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME, + new Function() { + @Override + public OffsetDateTime apply(TemporalAccessor temporalAccessor) { + return OffsetDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromIntegerArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public OffsetDateTime apply(FromDecimalArguments a) { + return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public OffsetDateTime apply(OffsetDateTime d, ZoneId z) { + return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime())); + } + } + ); + + public static final CustomInstantDeserializer ZONED_DATE_TIME = new CustomInstantDeserializer( + ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME, + new Function() { + @Override + public ZonedDateTime apply(TemporalAccessor temporalAccessor) { + return ZonedDateTime.from(temporalAccessor); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromIntegerArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId); + } + }, + new Function() { + @Override + public ZonedDateTime apply(FromDecimalArguments a) { + return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId); + } + }, + new BiFunction() { + @Override + public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) { + return zonedDateTime.withZoneSameInstant(zoneId); + } + } + ); + + protected final Function fromMilliseconds; + + protected final Function fromNanoseconds; + + protected final Function parsedToValue; + + protected final BiFunction adjust; + + protected CustomInstantDeserializer(Class supportedType, + DateTimeFormatter parser, + Function parsedToValue, + Function fromMilliseconds, + Function fromNanoseconds, + BiFunction adjust) { + super(supportedType, parser); + this.parsedToValue = parsedToValue; + this.fromMilliseconds = fromMilliseconds; + this.fromNanoseconds = fromNanoseconds; + this.adjust = adjust == null ? new BiFunction() { + @Override + public T apply(T t, ZoneId zoneId) { + return t; + } + } : adjust; + } + + @SuppressWarnings("unchecked") + protected CustomInstantDeserializer(CustomInstantDeserializer base, DateTimeFormatter f) { + super((Class) base.handledType(), f); + parsedToValue = base.parsedToValue; + fromMilliseconds = base.fromMilliseconds; + fromNanoseconds = base.fromNanoseconds; + adjust = base.adjust; + } + + @Override + protected JsonDeserializer withDateFormat(DateTimeFormatter dtf) { + if (dtf == _formatter) { + return this; + } + return new CustomInstantDeserializer(this, dtf); + } + + @Override + public T deserialize(JsonParser parser, DeserializationContext context) throws IOException { + //NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only + //string values have to be adjusted to the configured TZ. + switch (parser.getCurrentTokenId()) { + case JsonTokenId.ID_NUMBER_FLOAT: { + BigDecimal value = parser.getDecimalValue(); + long seconds = value.longValue(); + int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds); + return fromNanoseconds.apply(new FromDecimalArguments( + seconds, nanoseconds, getZone(context))); + } + + case JsonTokenId.ID_NUMBER_INT: { + long timestamp = parser.getLongValue(); + if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) { + return this.fromNanoseconds.apply(new FromDecimalArguments( + timestamp, 0, this.getZone(context) + )); + } + return this.fromMilliseconds.apply(new FromIntegerArguments( + timestamp, this.getZone(context) + )); + } + + case JsonTokenId.ID_STRING: { + String string = parser.getText().trim(); + if (string.length() == 0) { + return null; + } + if (string.endsWith("+0000")) { + string = string.substring(0, string.length() - 5) + "Z"; + } + T value; + try { + TemporalAccessor acc = _formatter.parse(string); + value = parsedToValue.apply(acc); + if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) { + return adjust.apply(value, this.getZone(context)); + } + } catch (DateTimeException e) { + throw _peelDTE(e); + } + return value; + } + } + throw context.mappingException("Expected type float, integer, or string."); + } + + private ZoneId getZone(DeserializationContext context) { + // Instants are always in UTC, so don't waste compute cycles + return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone()); + } + + private static class FromIntegerArguments { + public final long value; + public final ZoneId zoneId; + + private FromIntegerArguments(long value, ZoneId zoneId) { + this.value = value; + this.zoneId = zoneId; + } + } + + private static class FromDecimalArguments { + public final long integer; + public final int fraction; + public final ZoneId zoneId; + + private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) { + this.integer = integer; + this.fraction = fraction; + this.zoneId = zoneId; + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/JSON.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/JSON.java new file mode 100644 index 000000000000..7e2afd3432b6 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/JSON.java @@ -0,0 +1,252 @@ +package org.openapitools.client; + +import org.threeten.bp.*; +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import org.openapitools.jackson.nullable.JsonNullableModule; +import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; + +import java.text.DateFormat; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.ext.ContextResolver; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class JSON implements ContextResolver { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); + mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); + ThreeTenModule module = new ThreeTenModule(); + module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT); + module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME); + module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME); + mapper.registerModule(module); + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + } + + /** + * Set the date format for JSON (de)serialization with Date properties. + * @param dateFormat Date format + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } + + /** + * Get the object mapper + * + * @return object mapper + */ + public ObjectMapper getMapper() { return mapper; } + + /** + * Returns the target model class that should be used to deserialize the input data. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param modelClass The class that contains the discriminator mappings. + */ + public static Class getClassForElement(JsonNode node, Class modelClass) { + ClassDiscriminatorMapping cdm = modelDiscriminators.get(modelClass); + if (cdm != null) { + return cdm.getClassForElement(node, new HashSet>()); + } + return null; + } + + /** + * Helper class to register the discriminator mappings. + */ + private static class ClassDiscriminatorMapping { + // The model class name. + Class modelClass; + // The name of the discriminator property. + String discriminatorName; + // The discriminator mappings for a model class. + Map> discriminatorMappings; + + // Constructs a new class discriminator. + ClassDiscriminatorMapping(Class cls, String propertyName, Map> mappings) { + modelClass = cls; + discriminatorName = propertyName; + discriminatorMappings = new HashMap>(); + if (mappings != null) { + discriminatorMappings.putAll(mappings); + } + } + + // Return the name of the discriminator property for this model class. + String getDiscriminatorPropertyName() { + return discriminatorName; + } + + // Return the discriminator value or null if the discriminator is not + // present in the payload. + String getDiscriminatorValue(JsonNode node) { + // Determine the value of the discriminator property in the input data. + if (discriminatorName != null) { + // Get the value of the discriminator property, if present in the input payload. + node = node.get(discriminatorName); + if (node != null && node.isValueNode()) { + String discrValue = node.asText(); + if (discrValue != null) { + return discrValue; + } + } + } + return null; + } + + /** + * Returns the target model class that should be used to deserialize the input data. + * This function can be invoked for anyOf/oneOf composed models with discriminator mappings. + * The discriminator mappings are used to determine the target model class. + * + * @param node The input data. + * @param visitedClasses The set of classes that have already been visited. + */ + Class getClassForElement(JsonNode node, Set> visitedClasses) { + if (visitedClasses.contains(modelClass)) { + // Class has already been visited. + return null; + } + // Determine the value of the discriminator property in the input data. + String discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + return null; + } + Class cls = discriminatorMappings.get(discrValue); + // It may not be sufficient to return this cls directly because that target class + // may itself be a composed schema, possibly with its own discriminator. + visitedClasses.add(modelClass); + for (Class childClass : discriminatorMappings.values()) { + ClassDiscriminatorMapping childCdm = modelDiscriminators.get(childClass); + if (childCdm == null) { + continue; + } + if (!discriminatorName.equals(childCdm.discriminatorName)) { + discrValue = getDiscriminatorValue(node); + if (discrValue == null) { + continue; + } + } + if (childCdm != null) { + // Recursively traverse the discriminator mappings. + Class childDiscr = childCdm.getClassForElement(node, visitedClasses); + if (childDiscr != null) { + return childDiscr; + } + } + } + return cls; + } + } + + /** + * Returns true if inst is an instance of modelClass in the OpenAPI model hierarchy. + * + * The Java class hierarchy is not implemented the same way as the OpenAPI model hierarchy, + * so it's not possible to use the instanceof keyword. + * + * @param modelClass A OpenAPI model class. + * @param inst The instance object. + */ + public static boolean isInstanceOf(Class modelClass, Object inst, Set> visitedClasses) { + if (modelClass.isInstance(inst)) { + // This handles the 'allOf' use case with single parent inheritance. + return true; + } + if (visitedClasses.contains(modelClass)) { + // This is to prevent infinite recursion when the composed schemas have + // a circular dependency. + return false; + } + visitedClasses.add(modelClass); + + // Traverse the oneOf/anyOf composed schemas. + Map descendants = modelDescendants.get(modelClass); + if (descendants != null) { + for (GenericType childType : descendants.values()) { + if (isInstanceOf(childType.getRawType(), inst, visitedClasses)) { + return true; + } + } + } + return false; + } + + /** + * A map of discriminators for all model classes. + */ + private static Map, ClassDiscriminatorMapping> modelDiscriminators = new HashMap, ClassDiscriminatorMapping>(); + + /** + * A map of oneOf/anyOf descendants for each model class. + */ + private static Map, Map> modelDescendants = new HashMap, Map>(); + + /** + * Register a model class discriminator. + * + * @param modelClass the model class + * @param discriminatorPropertyName the name of the discriminator property + * @param mappings a map with the discriminator mappings. + */ + public static void registerDiscriminator(Class modelClass, String discriminatorPropertyName, Map> mappings) { + ClassDiscriminatorMapping m = new ClassDiscriminatorMapping(modelClass, discriminatorPropertyName, mappings); + modelDiscriminators.put(modelClass, m); + } + + /** + * Register the oneOf/anyOf descendants of the modelClass. + * + * @param modelClass the model class + * @param descendants a map of oneOf/anyOf descendants. + */ + public static void registerDescendants(Class modelClass, Map descendants) { + modelDescendants.put(modelClass, descendants); + } + + private static JSON json; + + static + { + json = new JSON(); + } + + /** + * Get the default JSON instance. + * + * @return the default JSON instance + */ + public static JSON getDefault() { + return json; + } + + /** + * Set the default JSON instance. + * + * @param json JSON instance to be used + */ + public static void setDefault(JSON json) { + JSON.json = json; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Pair.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 000000000000..e62f20b92ee3 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) { + return; + } + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) { + return; + } + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) { + return false; + } + + if (arg.trim().isEmpty()) { + return false; + } + + return true; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 000000000000..9ed3230bd364 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,55 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return this; + } +} \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 000000000000..a1107a8690e4 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A describtion of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replaceAll("\\{" + name + "\\}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerVariable.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 000000000000..c2f13e216662 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,23 @@ +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/StringUtil.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 000000000000..baacf90a2b13 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/api/UsageApi.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/api/UsageApi.java new file mode 100644 index 000000000000..668cbec37c2d --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/api/UsageApi.java @@ -0,0 +1,287 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class UsageApi { + private ApiClient apiClient; + + public UsageApi() { + this(Configuration.getDefaultApiClient()); + } + + public UsageApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Get the API cilent + * + * @return API client + */ + public ApiClient getApiClient() { + return apiClient; + } + + /** + * Set the API cilent + * + * @param apiClient an instance of API client + */ + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Use any API key + * Use any API key + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object anyKey() throws ApiException { + return anyKeyWithHttpInfo().getData(); + } + + /** + * Use any API key + * Use any API key + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse anyKeyWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/any"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key", "api_key_query" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.anyKey", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } + /** + * Use both API keys + * Use both API keys + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object bothKeys() throws ApiException { + return bothKeysWithHttpInfo().getData(); + } + + /** + * Use both API keys + * Use both API keys + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse bothKeysWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/both"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key", "api_key_query" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.bothKeys", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } + /** + * Use API key in header + * Use API key in header + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object keyInHeader() throws ApiException { + return keyInHeaderWithHttpInfo().getData(); + } + + /** + * Use API key in header + * Use API key in header + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse keyInHeaderWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/header"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.keyInHeader", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } + /** + * Use API key in query + * Use API key in query + * @return Object + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public Object keyInQuery() throws ApiException { + return keyInQueryWithHttpInfo().getData(); + } + + /** + * Use API key in query + * Use API key in query + * @return ApiResponse<Object> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
Status Code Description Response Headers
200 successful operation -
+ */ + public ApiResponse keyInQueryWithHttpInfo() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query"; + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "api_key_query" }; + + GenericType localVarReturnType = new GenericType() {}; + + return apiClient.invokeAPI("UsageApi.keyInQuery", localVarPath, "GET", localVarQueryParams, localVarPostBody, + localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, + localVarAuthNames, localVarReturnType, false); + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..dc5960d01a69 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,79 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 000000000000..56295a0d83cd --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,33 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; + +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..cdf367d2a505 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import com.migcomponents.migbase64.Base64; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 000000000000..2bae057b7c42 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,62 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private String bearerToken; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return bearerToken; + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.bearerToken = bearerToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + if(bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 000000000000..618f7e4efd62 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,149 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.openapitools.client.ApiException; +import java.util.Objects; +import java.lang.reflect.Type; +import java.util.Map; +import javax.ws.rs.core.GenericType; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + @JsonValue + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullalble + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/test/java/org/openapitools/client/api/UsageApiTest.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/test/java/org/openapitools/client/api/UsageApiTest.java new file mode 100644 index 000000000000..4c5fc6feab40 --- /dev/null +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/test/java/org/openapitools/client/api/UsageApiTest.java @@ -0,0 +1,91 @@ +/* + * OpenAPI Extension x-auth-id-alias + * This specification shows how to use x-auth-id-alias extension for API keys. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.*; +import org.openapitools.client.auth.*; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for UsageApi + */ +public class UsageApiTest { + + private final UsageApi api = new UsageApi(); + + /** + * Use any API key + * + * Use any API key + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void anyKeyTest() throws ApiException { + //Object response = api.anyKey(); + // TODO: test validations + } + + /** + * Use both API keys + * + * Use both API keys + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void bothKeysTest() throws ApiException { + //Object response = api.bothKeys(); + // TODO: test validations + } + + /** + * Use API key in header + * + * Use API key in header + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void keyInHeaderTest() throws ApiException { + //Object response = api.keyInHeader(); + // TODO: test validations + } + + /** + * Use API key in query + * + * Use API key in query + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void keyInQueryTest() throws ApiException { + //Object response = api.keyInQuery(); + // TODO: test validations + } + +} diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go index 4456d5af6e73..8efc1bb8e664 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_fake_classname_tags123.go @@ -97,12 +97,12 @@ func (r apiTestClassnameRequest) Execute() (Client, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key_query"]; ok { + if apiKey, ok := auth["api_key_query"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarQueryParams.Add("api_key_query", key) } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go index 31bdd2c3cf87..318ee2f6ea28 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_pet.go @@ -489,12 +489,12 @@ func (r apiGetPetByIdRequest) Execute() (Pet, *_nethttp.Response, error) { if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key } diff --git a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go index 6d48bf45defb..1857755301cf 100644 --- a/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go +++ b/samples/openapi3/client/petstore/go-experimental/go-petstore/api_store.go @@ -176,12 +176,12 @@ func (r apiGetInventoryRequest) Execute() (map[string]int32, *_nethttp.Response, if r.ctx != nil { // API Key Authentication if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { - if auth, ok := auth["api_key"]; ok { + if apiKey, ok := auth["api_key"]; ok { var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key } else { - key = auth.Key + key = apiKey.Key } localVarHeaderParams["api_key"] = key }